diff --git a/dist/build.js b/dist/build.js index 09ccf27..3896997 100644 --- a/dist/build.js +++ b/dist/build.js @@ -18424,6 +18424,20 @@ function logging() { return cachedLogging; } +// src/error.ts +var ActionError = class extends Error { + constructor(message, options) { + super(message, options); + this.name = "ActionError"; + } +}; +function maybeToActionError(error) { + if (error instanceof Stainless.BadRequestError || error instanceof Stainless.AuthenticationError || error instanceof Stainless.PermissionDeniedError || error instanceof Stainless.NotFoundError || error instanceof Stainless.UnprocessableEntityError) { + return new ActionError(error.message, { cause: error }); + } + return error; +} + // src/logger.ts var LOG_LEVELS = { debug: 0, @@ -18508,11 +18522,14 @@ function createLoggerImpl(logContext) { error: errorFn, fatal(message, ...args) { errorFn(message, ...args); - process.stderr.write( - ` + const isActionError = args.some((arg) => arg instanceof ActionError); + if (!isActionError) { + process.stderr.write( + ` This is a bug. Please report it at ${BUG_REPORT_URL} ` - ); + ); + } }, child(childContext) { const { context, ...rest } = logContext; @@ -26871,7 +26888,8 @@ function wrapAction(actionType, fn) { actionType, successOrError: { result: "success" } }); - } catch (error) { + } catch (rawError) { + const error = maybeToActionError(rawError); logger.fatal("Error in action:", error); if (stainless) { await maybeReportResult({ diff --git a/dist/checkoutPRRef.js b/dist/checkoutPRRef.js index b0fd62e..fcdbfcc 100644 --- a/dist/checkoutPRRef.js +++ b/dist/checkoutPRRef.js @@ -2640,7 +2640,7 @@ var require_libsodium_wrappers = __commonJS({ var r2, t = "uint8array", _ = a2.ready.then((function() { function t2() { if (0 !== r2._sodium_init()) throw new Error("libsodium was not correctly initialized."); - for (var a3 = ["crypto_aead_aegis128l_decrypt", "crypto_aead_aegis128l_decrypt_detached", "crypto_aead_aegis128l_encrypt", "crypto_aead_aegis128l_encrypt_detached", "crypto_aead_aegis128l_keygen", "crypto_aead_aegis256_decrypt", "crypto_aead_aegis256_decrypt_detached", "crypto_aead_aegis256_encrypt", "crypto_aead_aegis256_encrypt_detached", "crypto_aead_aegis256_keygen", "crypto_aead_chacha20poly1305_decrypt", "crypto_aead_chacha20poly1305_decrypt_detached", "crypto_aead_chacha20poly1305_encrypt", "crypto_aead_chacha20poly1305_encrypt_detached", "crypto_aead_chacha20poly1305_ietf_decrypt", "crypto_aead_chacha20poly1305_ietf_decrypt_detached", "crypto_aead_chacha20poly1305_ietf_encrypt", "crypto_aead_chacha20poly1305_ietf_encrypt_detached", "crypto_aead_chacha20poly1305_ietf_keygen", "crypto_aead_chacha20poly1305_keygen", "crypto_aead_xchacha20poly1305_ietf_decrypt", "crypto_aead_xchacha20poly1305_ietf_decrypt_detached", "crypto_aead_xchacha20poly1305_ietf_encrypt", "crypto_aead_xchacha20poly1305_ietf_encrypt_detached", "crypto_aead_xchacha20poly1305_ietf_keygen", "crypto_auth", "crypto_auth_hmacsha256", "crypto_auth_hmacsha256_final", "crypto_auth_hmacsha256_init", "crypto_auth_hmacsha256_keygen", "crypto_auth_hmacsha256_update", "crypto_auth_hmacsha256_verify", "crypto_auth_hmacsha512", "crypto_auth_hmacsha512256", "crypto_auth_hmacsha512256_final", "crypto_auth_hmacsha512256_init", "crypto_auth_hmacsha512256_keygen", "crypto_auth_hmacsha512256_update", "crypto_auth_hmacsha512256_verify", "crypto_auth_hmacsha512_final", "crypto_auth_hmacsha512_init", "crypto_auth_hmacsha512_keygen", "crypto_auth_hmacsha512_update", "crypto_auth_hmacsha512_verify", "crypto_auth_keygen", "crypto_auth_verify", "crypto_box_beforenm", "crypto_box_curve25519xchacha20poly1305_beforenm", "crypto_box_curve25519xchacha20poly1305_detached", "crypto_box_curve25519xchacha20poly1305_detached_afternm", "crypto_box_curve25519xchacha20poly1305_easy", "crypto_box_curve25519xchacha20poly1305_easy_afternm", "crypto_box_curve25519xchacha20poly1305_keypair", "crypto_box_curve25519xchacha20poly1305_open_detached", "crypto_box_curve25519xchacha20poly1305_open_detached_afternm", "crypto_box_curve25519xchacha20poly1305_open_easy", "crypto_box_curve25519xchacha20poly1305_open_easy_afternm", "crypto_box_curve25519xchacha20poly1305_seal", "crypto_box_curve25519xchacha20poly1305_seal_open", "crypto_box_curve25519xchacha20poly1305_seed_keypair", "crypto_box_detached", "crypto_box_easy", "crypto_box_easy_afternm", "crypto_box_keypair", "crypto_box_open_detached", "crypto_box_open_easy", "crypto_box_open_easy_afternm", "crypto_box_seal", "crypto_box_seal_open", "crypto_box_seed_keypair", "crypto_core_ed25519_add", "crypto_core_ed25519_from_hash", "crypto_core_ed25519_from_uniform", "crypto_core_ed25519_is_valid_point", "crypto_core_ed25519_random", "crypto_core_ed25519_scalar_add", "crypto_core_ed25519_scalar_complement", "crypto_core_ed25519_scalar_invert", "crypto_core_ed25519_scalar_mul", "crypto_core_ed25519_scalar_negate", "crypto_core_ed25519_scalar_random", "crypto_core_ed25519_scalar_reduce", "crypto_core_ed25519_scalar_sub", "crypto_core_ed25519_sub", "crypto_core_hchacha20", "crypto_core_hsalsa20", "crypto_core_ristretto255_add", "crypto_core_ristretto255_from_hash", "crypto_core_ristretto255_is_valid_point", "crypto_core_ristretto255_random", "crypto_core_ristretto255_scalar_add", "crypto_core_ristretto255_scalar_complement", "crypto_core_ristretto255_scalar_invert", "crypto_core_ristretto255_scalar_mul", "crypto_core_ristretto255_scalar_negate", "crypto_core_ristretto255_scalar_random", "crypto_core_ristretto255_scalar_reduce", "crypto_core_ristretto255_scalar_sub", "crypto_core_ristretto255_sub", "crypto_generichash", "crypto_generichash_blake2b_salt_personal", "crypto_generichash_final", "crypto_generichash_init", "crypto_generichash_keygen", "crypto_generichash_update", "crypto_hash", "crypto_hash_sha256", "crypto_hash_sha256_final", "crypto_hash_sha256_init", "crypto_hash_sha256_update", "crypto_hash_sha512", "crypto_hash_sha512_final", "crypto_hash_sha512_init", "crypto_hash_sha512_update", "crypto_kdf_derive_from_key", "crypto_kdf_keygen", "crypto_kx_client_session_keys", "crypto_kx_keypair", "crypto_kx_seed_keypair", "crypto_kx_server_session_keys", "crypto_onetimeauth", "crypto_onetimeauth_final", "crypto_onetimeauth_init", "crypto_onetimeauth_keygen", "crypto_onetimeauth_update", "crypto_onetimeauth_verify", "crypto_pwhash", "crypto_pwhash_scryptsalsa208sha256", "crypto_pwhash_scryptsalsa208sha256_ll", "crypto_pwhash_scryptsalsa208sha256_str", "crypto_pwhash_scryptsalsa208sha256_str_verify", "crypto_pwhash_str", "crypto_pwhash_str_needs_rehash", "crypto_pwhash_str_verify", "crypto_scalarmult", "crypto_scalarmult_base", "crypto_scalarmult_ed25519", "crypto_scalarmult_ed25519_base", "crypto_scalarmult_ed25519_base_noclamp", "crypto_scalarmult_ed25519_noclamp", "crypto_scalarmult_ristretto255", "crypto_scalarmult_ristretto255_base", "crypto_secretbox_detached", "crypto_secretbox_easy", "crypto_secretbox_keygen", "crypto_secretbox_open_detached", "crypto_secretbox_open_easy", "crypto_secretstream_xchacha20poly1305_init_pull", "crypto_secretstream_xchacha20poly1305_init_push", "crypto_secretstream_xchacha20poly1305_keygen", "crypto_secretstream_xchacha20poly1305_pull", "crypto_secretstream_xchacha20poly1305_push", "crypto_secretstream_xchacha20poly1305_rekey", "crypto_shorthash", "crypto_shorthash_keygen", "crypto_shorthash_siphashx24", "crypto_sign", "crypto_sign_detached", "crypto_sign_ed25519_pk_to_curve25519", "crypto_sign_ed25519_sk_to_curve25519", "crypto_sign_ed25519_sk_to_pk", "crypto_sign_ed25519_sk_to_seed", "crypto_sign_final_create", "crypto_sign_final_verify", "crypto_sign_init", "crypto_sign_keypair", "crypto_sign_open", "crypto_sign_seed_keypair", "crypto_sign_update", "crypto_sign_verify_detached", "crypto_stream_chacha20", "crypto_stream_chacha20_ietf_xor", "crypto_stream_chacha20_ietf_xor_ic", "crypto_stream_chacha20_keygen", "crypto_stream_chacha20_xor", "crypto_stream_chacha20_xor_ic", "crypto_stream_keygen", "crypto_stream_xchacha20_keygen", "crypto_stream_xchacha20_xor", "crypto_stream_xchacha20_xor_ic", "randombytes_buf", "randombytes_buf_deterministic", "randombytes_close", "randombytes_random", "randombytes_set_implementation", "randombytes_stir", "randombytes_uniform", "sodium_version_string"], t3 = [x, k, S, T, w, Y, B, A, M, I, K, N, L, O, U, C, P, R, X, G, D, F, V3, H, W, q, j, z, J, Q, Z, $, ee, ae, re, te, _e, ne, se, ce, he, oe, pe, ye, ie, le, ue, de, ve, ge, be, fe, me, Ee, xe, ke, Se, Te, we, Ye, Be, Ae, Me, Ie, Ke, Ne, Le, Oe, Ue, Ce, Pe, Re, Xe, Ge, De, Fe, Ve, He, We, qe, je, ze, Je, Qe, Ze, $e, ea, aa, ra, ta, _a, na, sa, ca, ha, oa, pa, ya, ia, la, ua, da, va, ga, ba, fa, ma, Ea, xa, ka, Sa, Ta, wa, Ya, Ba, Aa, Ma, Ia, Ka, Na, La, Oa, Ua, Ca, Pa, Ra, Xa, Ga, Da, Fa, Va, Ha, Wa, qa, ja, za, Ja, Qa, Za, $a, er, ar, rr, tr, _r, nr, sr, cr, hr, or, pr, yr, ir, lr, ur, dr, vr, gr, br, fr, mr, Er, xr, kr, Sr, Tr, wr, Yr, Br, Ar, Mr, Ir, Kr, Nr, Lr, Or, Ur, Cr, Pr, Rr, Xr, Gr, Dr, Fr, Vr, Hr, Wr, qr], _3 = 0; _3 < t3.length; _3++) "function" == typeof r2["_" + a3[_3]] && (e2[a3[_3]] = t3[_3]); + for (var a3 = ["crypto_aead_aegis128l_decrypt", "crypto_aead_aegis128l_decrypt_detached", "crypto_aead_aegis128l_encrypt", "crypto_aead_aegis128l_encrypt_detached", "crypto_aead_aegis128l_keygen", "crypto_aead_aegis256_decrypt", "crypto_aead_aegis256_decrypt_detached", "crypto_aead_aegis256_encrypt", "crypto_aead_aegis256_encrypt_detached", "crypto_aead_aegis256_keygen", "crypto_aead_chacha20poly1305_decrypt", "crypto_aead_chacha20poly1305_decrypt_detached", "crypto_aead_chacha20poly1305_encrypt", "crypto_aead_chacha20poly1305_encrypt_detached", "crypto_aead_chacha20poly1305_ietf_decrypt", "crypto_aead_chacha20poly1305_ietf_decrypt_detached", "crypto_aead_chacha20poly1305_ietf_encrypt", "crypto_aead_chacha20poly1305_ietf_encrypt_detached", "crypto_aead_chacha20poly1305_ietf_keygen", "crypto_aead_chacha20poly1305_keygen", "crypto_aead_xchacha20poly1305_ietf_decrypt", "crypto_aead_xchacha20poly1305_ietf_decrypt_detached", "crypto_aead_xchacha20poly1305_ietf_encrypt", "crypto_aead_xchacha20poly1305_ietf_encrypt_detached", "crypto_aead_xchacha20poly1305_ietf_keygen", "crypto_auth", "crypto_auth_hmacsha256", "crypto_auth_hmacsha256_final", "crypto_auth_hmacsha256_init", "crypto_auth_hmacsha256_keygen", "crypto_auth_hmacsha256_update", "crypto_auth_hmacsha256_verify", "crypto_auth_hmacsha512", "crypto_auth_hmacsha512256", "crypto_auth_hmacsha512256_final", "crypto_auth_hmacsha512256_init", "crypto_auth_hmacsha512256_keygen", "crypto_auth_hmacsha512256_update", "crypto_auth_hmacsha512256_verify", "crypto_auth_hmacsha512_final", "crypto_auth_hmacsha512_init", "crypto_auth_hmacsha512_keygen", "crypto_auth_hmacsha512_update", "crypto_auth_hmacsha512_verify", "crypto_auth_keygen", "crypto_auth_verify", "crypto_box_beforenm", "crypto_box_curve25519xchacha20poly1305_beforenm", "crypto_box_curve25519xchacha20poly1305_detached", "crypto_box_curve25519xchacha20poly1305_detached_afternm", "crypto_box_curve25519xchacha20poly1305_easy", "crypto_box_curve25519xchacha20poly1305_easy_afternm", "crypto_box_curve25519xchacha20poly1305_keypair", "crypto_box_curve25519xchacha20poly1305_open_detached", "crypto_box_curve25519xchacha20poly1305_open_detached_afternm", "crypto_box_curve25519xchacha20poly1305_open_easy", "crypto_box_curve25519xchacha20poly1305_open_easy_afternm", "crypto_box_curve25519xchacha20poly1305_seal", "crypto_box_curve25519xchacha20poly1305_seal_open", "crypto_box_curve25519xchacha20poly1305_seed_keypair", "crypto_box_detached", "crypto_box_easy", "crypto_box_easy_afternm", "crypto_box_keypair", "crypto_box_open_detached", "crypto_box_open_easy", "crypto_box_open_easy_afternm", "crypto_box_seal", "crypto_box_seal_open", "crypto_box_seed_keypair", "crypto_core_ed25519_add", "crypto_core_ed25519_from_hash", "crypto_core_ed25519_from_uniform", "crypto_core_ed25519_is_valid_point", "crypto_core_ed25519_random", "crypto_core_ed25519_scalar_add", "crypto_core_ed25519_scalar_complement", "crypto_core_ed25519_scalar_invert", "crypto_core_ed25519_scalar_mul", "crypto_core_ed25519_scalar_negate", "crypto_core_ed25519_scalar_random", "crypto_core_ed25519_scalar_reduce", "crypto_core_ed25519_scalar_sub", "crypto_core_ed25519_sub", "crypto_core_hchacha20", "crypto_core_hsalsa20", "crypto_core_ristretto255_add", "crypto_core_ristretto255_from_hash", "crypto_core_ristretto255_is_valid_point", "crypto_core_ristretto255_random", "crypto_core_ristretto255_scalar_add", "crypto_core_ristretto255_scalar_complement", "crypto_core_ristretto255_scalar_invert", "crypto_core_ristretto255_scalar_mul", "crypto_core_ristretto255_scalar_negate", "crypto_core_ristretto255_scalar_random", "crypto_core_ristretto255_scalar_reduce", "crypto_core_ristretto255_scalar_sub", "crypto_core_ristretto255_sub", "crypto_generichash", "crypto_generichash_blake2b_salt_personal", "crypto_generichash_final", "crypto_generichash_init", "crypto_generichash_keygen", "crypto_generichash_update", "crypto_hash", "crypto_hash_sha256", "crypto_hash_sha256_final", "crypto_hash_sha256_init", "crypto_hash_sha256_update", "crypto_hash_sha512", "crypto_hash_sha512_final", "crypto_hash_sha512_init", "crypto_hash_sha512_update", "crypto_kdf_derive_from_key", "crypto_kdf_keygen", "crypto_kx_client_session_keys", "crypto_kx_keypair", "crypto_kx_seed_keypair", "crypto_kx_server_session_keys", "crypto_onetimeauth", "crypto_onetimeauth_final", "crypto_onetimeauth_init", "crypto_onetimeauth_keygen", "crypto_onetimeauth_update", "crypto_onetimeauth_verify", "crypto_pwhash", "crypto_pwhash_scryptsalsa208sha256", "crypto_pwhash_scryptsalsa208sha256_ll", "crypto_pwhash_scryptsalsa208sha256_str", "crypto_pwhash_scryptsalsa208sha256_str_verify", "crypto_pwhash_str", "crypto_pwhash_str_needs_rehash", "crypto_pwhash_str_verify", "crypto_scalarmult", "crypto_scalarmult_base", "crypto_scalarmult_ed25519", "crypto_scalarmult_ed25519_base", "crypto_scalarmult_ed25519_base_noclamp", "crypto_scalarmult_ed25519_noclamp", "crypto_scalarmult_ristretto255", "crypto_scalarmult_ristretto255_base", "crypto_secretbox_detached", "crypto_secretbox_easy", "crypto_secretbox_keygen", "crypto_secretbox_open_detached", "crypto_secretbox_open_easy", "crypto_secretstream_xchacha20poly1305_init_pull", "crypto_secretstream_xchacha20poly1305_init_push", "crypto_secretstream_xchacha20poly1305_keygen", "crypto_secretstream_xchacha20poly1305_pull", "crypto_secretstream_xchacha20poly1305_push", "crypto_secretstream_xchacha20poly1305_rekey", "crypto_shorthash", "crypto_shorthash_keygen", "crypto_shorthash_siphashx24", "crypto_sign", "crypto_sign_detached", "crypto_sign_ed25519_pk_to_curve25519", "crypto_sign_ed25519_sk_to_curve25519", "crypto_sign_ed25519_sk_to_pk", "crypto_sign_ed25519_sk_to_seed", "crypto_sign_final_create", "crypto_sign_final_verify", "crypto_sign_init", "crypto_sign_keypair", "crypto_sign_open", "crypto_sign_seed_keypair", "crypto_sign_update", "crypto_sign_verify_detached", "crypto_stream_chacha20", "crypto_stream_chacha20_ietf_xor", "crypto_stream_chacha20_ietf_xor_ic", "crypto_stream_chacha20_keygen", "crypto_stream_chacha20_xor", "crypto_stream_chacha20_xor_ic", "crypto_stream_keygen", "crypto_stream_xchacha20_keygen", "crypto_stream_xchacha20_xor", "crypto_stream_xchacha20_xor_ic", "randombytes_buf", "randombytes_buf_deterministic", "randombytes_close", "randombytes_random", "randombytes_set_implementation", "randombytes_stir", "randombytes_uniform", "sodium_version_string"], t3 = [x, k, S, T, w, Y, B, A, M, I, K, N, L, O, U, C, P, R, X, G, D, F, V3, H, W, q, j, z, J, Q, Z, $, ee, ae, re, te, _e, ne, se, ce, he, oe, pe, ye, ie, le, ue, de, ve, ge, be, fe, me, Ee, xe, ke, Se, Te, we, Ye, Be, Ae, Me, Ie, Ke, Ne, Le, Oe, Ue, Ce, Pe, Re, Xe, Ge, De, Fe, Ve, He, We, qe, je, ze, Je, Qe, Ze, $e, ea, aa, ra, ta, _a2, na, sa, ca, ha, oa, pa, ya, ia, la, ua, da, va, ga, ba, fa, ma, Ea, xa, ka, Sa, Ta, wa, Ya, Ba, Aa, Ma, Ia, Ka, Na, La, Oa, Ua, Ca, Pa, Ra, Xa, Ga, Da, Fa, Va, Ha, Wa, qa, ja, za, Ja, Qa, Za, $a, er, ar, rr, tr, _r, nr, sr, cr, hr, or, pr, yr, ir, lr, ur, dr, vr, gr, br, fr, mr, Er, xr, kr, Sr, Tr, wr, Yr, Br, Ar, Mr, Ir, Kr, Nr, Lr, Or, Ur, Cr, Pr, Rr, Xr, Gr, Dr, Fr, Vr, Hr, Wr, qr], _3 = 0; _3 < t3.length; _3++) "function" == typeof r2["_" + a3[_3]] && (e2[a3[_3]] = t3[_3]); var n3 = ["SODIUM_LIBRARY_VERSION_MAJOR", "SODIUM_LIBRARY_VERSION_MINOR", "crypto_aead_aegis128l_ABYTES", "crypto_aead_aegis128l_KEYBYTES", "crypto_aead_aegis128l_MESSAGEBYTES_MAX", "crypto_aead_aegis128l_NPUBBYTES", "crypto_aead_aegis128l_NSECBYTES", "crypto_aead_aegis256_ABYTES", "crypto_aead_aegis256_KEYBYTES", "crypto_aead_aegis256_MESSAGEBYTES_MAX", "crypto_aead_aegis256_NPUBBYTES", "crypto_aead_aegis256_NSECBYTES", "crypto_aead_aes256gcm_ABYTES", "crypto_aead_aes256gcm_KEYBYTES", "crypto_aead_aes256gcm_MESSAGEBYTES_MAX", "crypto_aead_aes256gcm_NPUBBYTES", "crypto_aead_aes256gcm_NSECBYTES", "crypto_aead_chacha20poly1305_ABYTES", "crypto_aead_chacha20poly1305_IETF_ABYTES", "crypto_aead_chacha20poly1305_IETF_KEYBYTES", "crypto_aead_chacha20poly1305_IETF_MESSAGEBYTES_MAX", "crypto_aead_chacha20poly1305_IETF_NPUBBYTES", "crypto_aead_chacha20poly1305_IETF_NSECBYTES", "crypto_aead_chacha20poly1305_KEYBYTES", "crypto_aead_chacha20poly1305_MESSAGEBYTES_MAX", "crypto_aead_chacha20poly1305_NPUBBYTES", "crypto_aead_chacha20poly1305_NSECBYTES", "crypto_aead_chacha20poly1305_ietf_ABYTES", "crypto_aead_chacha20poly1305_ietf_KEYBYTES", "crypto_aead_chacha20poly1305_ietf_MESSAGEBYTES_MAX", "crypto_aead_chacha20poly1305_ietf_NPUBBYTES", "crypto_aead_chacha20poly1305_ietf_NSECBYTES", "crypto_aead_xchacha20poly1305_IETF_ABYTES", "crypto_aead_xchacha20poly1305_IETF_KEYBYTES", "crypto_aead_xchacha20poly1305_IETF_MESSAGEBYTES_MAX", "crypto_aead_xchacha20poly1305_IETF_NPUBBYTES", "crypto_aead_xchacha20poly1305_IETF_NSECBYTES", "crypto_aead_xchacha20poly1305_ietf_ABYTES", "crypto_aead_xchacha20poly1305_ietf_KEYBYTES", "crypto_aead_xchacha20poly1305_ietf_MESSAGEBYTES_MAX", "crypto_aead_xchacha20poly1305_ietf_NPUBBYTES", "crypto_aead_xchacha20poly1305_ietf_NSECBYTES", "crypto_auth_BYTES", "crypto_auth_KEYBYTES", "crypto_auth_hmacsha256_BYTES", "crypto_auth_hmacsha256_KEYBYTES", "crypto_auth_hmacsha512256_BYTES", "crypto_auth_hmacsha512256_KEYBYTES", "crypto_auth_hmacsha512_BYTES", "crypto_auth_hmacsha512_KEYBYTES", "crypto_box_BEFORENMBYTES", "crypto_box_MACBYTES", "crypto_box_MESSAGEBYTES_MAX", "crypto_box_NONCEBYTES", "crypto_box_PUBLICKEYBYTES", "crypto_box_SEALBYTES", "crypto_box_SECRETKEYBYTES", "crypto_box_SEEDBYTES", "crypto_box_curve25519xchacha20poly1305_BEFORENMBYTES", "crypto_box_curve25519xchacha20poly1305_MACBYTES", "crypto_box_curve25519xchacha20poly1305_MESSAGEBYTES_MAX", "crypto_box_curve25519xchacha20poly1305_NONCEBYTES", "crypto_box_curve25519xchacha20poly1305_PUBLICKEYBYTES", "crypto_box_curve25519xchacha20poly1305_SEALBYTES", "crypto_box_curve25519xchacha20poly1305_SECRETKEYBYTES", "crypto_box_curve25519xchacha20poly1305_SEEDBYTES", "crypto_box_curve25519xsalsa20poly1305_BEFORENMBYTES", "crypto_box_curve25519xsalsa20poly1305_MACBYTES", "crypto_box_curve25519xsalsa20poly1305_MESSAGEBYTES_MAX", "crypto_box_curve25519xsalsa20poly1305_NONCEBYTES", "crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES", "crypto_box_curve25519xsalsa20poly1305_SECRETKEYBYTES", "crypto_box_curve25519xsalsa20poly1305_SEEDBYTES", "crypto_core_ed25519_BYTES", "crypto_core_ed25519_HASHBYTES", "crypto_core_ed25519_NONREDUCEDSCALARBYTES", "crypto_core_ed25519_SCALARBYTES", "crypto_core_ed25519_UNIFORMBYTES", "crypto_core_hchacha20_CONSTBYTES", "crypto_core_hchacha20_INPUTBYTES", "crypto_core_hchacha20_KEYBYTES", "crypto_core_hchacha20_OUTPUTBYTES", "crypto_core_hsalsa20_CONSTBYTES", "crypto_core_hsalsa20_INPUTBYTES", "crypto_core_hsalsa20_KEYBYTES", "crypto_core_hsalsa20_OUTPUTBYTES", "crypto_core_ristretto255_BYTES", "crypto_core_ristretto255_HASHBYTES", "crypto_core_ristretto255_NONREDUCEDSCALARBYTES", "crypto_core_ristretto255_SCALARBYTES", "crypto_core_salsa2012_CONSTBYTES", "crypto_core_salsa2012_INPUTBYTES", "crypto_core_salsa2012_KEYBYTES", "crypto_core_salsa2012_OUTPUTBYTES", "crypto_core_salsa208_CONSTBYTES", "crypto_core_salsa208_INPUTBYTES", "crypto_core_salsa208_KEYBYTES", "crypto_core_salsa208_OUTPUTBYTES", "crypto_core_salsa20_CONSTBYTES", "crypto_core_salsa20_INPUTBYTES", "crypto_core_salsa20_KEYBYTES", "crypto_core_salsa20_OUTPUTBYTES", "crypto_generichash_BYTES", "crypto_generichash_BYTES_MAX", "crypto_generichash_BYTES_MIN", "crypto_generichash_KEYBYTES", "crypto_generichash_KEYBYTES_MAX", "crypto_generichash_KEYBYTES_MIN", "crypto_generichash_blake2b_BYTES", "crypto_generichash_blake2b_BYTES_MAX", "crypto_generichash_blake2b_BYTES_MIN", "crypto_generichash_blake2b_KEYBYTES", "crypto_generichash_blake2b_KEYBYTES_MAX", "crypto_generichash_blake2b_KEYBYTES_MIN", "crypto_generichash_blake2b_PERSONALBYTES", "crypto_generichash_blake2b_SALTBYTES", "crypto_hash_BYTES", "crypto_hash_sha256_BYTES", "crypto_hash_sha512_BYTES", "crypto_kdf_BYTES_MAX", "crypto_kdf_BYTES_MIN", "crypto_kdf_CONTEXTBYTES", "crypto_kdf_KEYBYTES", "crypto_kdf_blake2b_BYTES_MAX", "crypto_kdf_blake2b_BYTES_MIN", "crypto_kdf_blake2b_CONTEXTBYTES", "crypto_kdf_blake2b_KEYBYTES", "crypto_kdf_hkdf_sha256_BYTES_MAX", "crypto_kdf_hkdf_sha256_BYTES_MIN", "crypto_kdf_hkdf_sha256_KEYBYTES", "crypto_kdf_hkdf_sha512_BYTES_MAX", "crypto_kdf_hkdf_sha512_BYTES_MIN", "crypto_kdf_hkdf_sha512_KEYBYTES", "crypto_kx_PUBLICKEYBYTES", "crypto_kx_SECRETKEYBYTES", "crypto_kx_SEEDBYTES", "crypto_kx_SESSIONKEYBYTES", "crypto_onetimeauth_BYTES", "crypto_onetimeauth_KEYBYTES", "crypto_onetimeauth_poly1305_BYTES", "crypto_onetimeauth_poly1305_KEYBYTES", "crypto_pwhash_ALG_ARGON2I13", "crypto_pwhash_ALG_ARGON2ID13", "crypto_pwhash_ALG_DEFAULT", "crypto_pwhash_BYTES_MAX", "crypto_pwhash_BYTES_MIN", "crypto_pwhash_MEMLIMIT_INTERACTIVE", "crypto_pwhash_MEMLIMIT_MAX", "crypto_pwhash_MEMLIMIT_MIN", "crypto_pwhash_MEMLIMIT_MODERATE", "crypto_pwhash_MEMLIMIT_SENSITIVE", "crypto_pwhash_OPSLIMIT_INTERACTIVE", "crypto_pwhash_OPSLIMIT_MAX", "crypto_pwhash_OPSLIMIT_MIN", "crypto_pwhash_OPSLIMIT_MODERATE", "crypto_pwhash_OPSLIMIT_SENSITIVE", "crypto_pwhash_PASSWD_MAX", "crypto_pwhash_PASSWD_MIN", "crypto_pwhash_SALTBYTES", "crypto_pwhash_STRBYTES", "crypto_pwhash_argon2i_BYTES_MAX", "crypto_pwhash_argon2i_BYTES_MIN", "crypto_pwhash_argon2i_MEMLIMIT_INTERACTIVE", "crypto_pwhash_argon2i_MEMLIMIT_MAX", "crypto_pwhash_argon2i_MEMLIMIT_MIN", "crypto_pwhash_argon2i_MEMLIMIT_MODERATE", "crypto_pwhash_argon2i_MEMLIMIT_SENSITIVE", "crypto_pwhash_argon2i_OPSLIMIT_INTERACTIVE", "crypto_pwhash_argon2i_OPSLIMIT_MAX", "crypto_pwhash_argon2i_OPSLIMIT_MIN", "crypto_pwhash_argon2i_OPSLIMIT_MODERATE", "crypto_pwhash_argon2i_OPSLIMIT_SENSITIVE", "crypto_pwhash_argon2i_PASSWD_MAX", "crypto_pwhash_argon2i_PASSWD_MIN", "crypto_pwhash_argon2i_SALTBYTES", "crypto_pwhash_argon2i_STRBYTES", "crypto_pwhash_argon2id_BYTES_MAX", "crypto_pwhash_argon2id_BYTES_MIN", "crypto_pwhash_argon2id_MEMLIMIT_INTERACTIVE", "crypto_pwhash_argon2id_MEMLIMIT_MAX", "crypto_pwhash_argon2id_MEMLIMIT_MIN", "crypto_pwhash_argon2id_MEMLIMIT_MODERATE", "crypto_pwhash_argon2id_MEMLIMIT_SENSITIVE", "crypto_pwhash_argon2id_OPSLIMIT_INTERACTIVE", "crypto_pwhash_argon2id_OPSLIMIT_MAX", "crypto_pwhash_argon2id_OPSLIMIT_MIN", "crypto_pwhash_argon2id_OPSLIMIT_MODERATE", "crypto_pwhash_argon2id_OPSLIMIT_SENSITIVE", "crypto_pwhash_argon2id_PASSWD_MAX", "crypto_pwhash_argon2id_PASSWD_MIN", "crypto_pwhash_argon2id_SALTBYTES", "crypto_pwhash_argon2id_STRBYTES", "crypto_pwhash_scryptsalsa208sha256_BYTES_MAX", "crypto_pwhash_scryptsalsa208sha256_BYTES_MIN", "crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_INTERACTIVE", "crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX", "crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN", "crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_SENSITIVE", "crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_INTERACTIVE", "crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX", "crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN", "crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_SENSITIVE", "crypto_pwhash_scryptsalsa208sha256_PASSWD_MAX", "crypto_pwhash_scryptsalsa208sha256_PASSWD_MIN", "crypto_pwhash_scryptsalsa208sha256_SALTBYTES", "crypto_pwhash_scryptsalsa208sha256_STRBYTES", "crypto_scalarmult_BYTES", "crypto_scalarmult_SCALARBYTES", "crypto_scalarmult_curve25519_BYTES", "crypto_scalarmult_curve25519_SCALARBYTES", "crypto_scalarmult_ed25519_BYTES", "crypto_scalarmult_ed25519_SCALARBYTES", "crypto_scalarmult_ristretto255_BYTES", "crypto_scalarmult_ristretto255_SCALARBYTES", "crypto_secretbox_KEYBYTES", "crypto_secretbox_MACBYTES", "crypto_secretbox_MESSAGEBYTES_MAX", "crypto_secretbox_NONCEBYTES", "crypto_secretbox_xchacha20poly1305_KEYBYTES", "crypto_secretbox_xchacha20poly1305_MACBYTES", "crypto_secretbox_xchacha20poly1305_MESSAGEBYTES_MAX", "crypto_secretbox_xchacha20poly1305_NONCEBYTES", "crypto_secretbox_xsalsa20poly1305_KEYBYTES", "crypto_secretbox_xsalsa20poly1305_MACBYTES", "crypto_secretbox_xsalsa20poly1305_MESSAGEBYTES_MAX", "crypto_secretbox_xsalsa20poly1305_NONCEBYTES", "crypto_secretstream_xchacha20poly1305_ABYTES", "crypto_secretstream_xchacha20poly1305_HEADERBYTES", "crypto_secretstream_xchacha20poly1305_KEYBYTES", "crypto_secretstream_xchacha20poly1305_MESSAGEBYTES_MAX", "crypto_secretstream_xchacha20poly1305_TAG_FINAL", "crypto_secretstream_xchacha20poly1305_TAG_MESSAGE", "crypto_secretstream_xchacha20poly1305_TAG_PUSH", "crypto_secretstream_xchacha20poly1305_TAG_REKEY", "crypto_shorthash_BYTES", "crypto_shorthash_KEYBYTES", "crypto_shorthash_siphash24_BYTES", "crypto_shorthash_siphash24_KEYBYTES", "crypto_shorthash_siphashx24_BYTES", "crypto_shorthash_siphashx24_KEYBYTES", "crypto_sign_BYTES", "crypto_sign_MESSAGEBYTES_MAX", "crypto_sign_PUBLICKEYBYTES", "crypto_sign_SECRETKEYBYTES", "crypto_sign_SEEDBYTES", "crypto_sign_ed25519_BYTES", "crypto_sign_ed25519_MESSAGEBYTES_MAX", "crypto_sign_ed25519_PUBLICKEYBYTES", "crypto_sign_ed25519_SECRETKEYBYTES", "crypto_sign_ed25519_SEEDBYTES", "crypto_stream_KEYBYTES", "crypto_stream_MESSAGEBYTES_MAX", "crypto_stream_NONCEBYTES", "crypto_stream_chacha20_IETF_KEYBYTES", "crypto_stream_chacha20_IETF_MESSAGEBYTES_MAX", "crypto_stream_chacha20_IETF_NONCEBYTES", "crypto_stream_chacha20_KEYBYTES", "crypto_stream_chacha20_MESSAGEBYTES_MAX", "crypto_stream_chacha20_NONCEBYTES", "crypto_stream_chacha20_ietf_KEYBYTES", "crypto_stream_chacha20_ietf_MESSAGEBYTES_MAX", "crypto_stream_chacha20_ietf_NONCEBYTES", "crypto_stream_salsa2012_KEYBYTES", "crypto_stream_salsa2012_MESSAGEBYTES_MAX", "crypto_stream_salsa2012_NONCEBYTES", "crypto_stream_salsa208_KEYBYTES", "crypto_stream_salsa208_MESSAGEBYTES_MAX", "crypto_stream_salsa208_NONCEBYTES", "crypto_stream_salsa20_KEYBYTES", "crypto_stream_salsa20_MESSAGEBYTES_MAX", "crypto_stream_salsa20_NONCEBYTES", "crypto_stream_xchacha20_KEYBYTES", "crypto_stream_xchacha20_MESSAGEBYTES_MAX", "crypto_stream_xchacha20_NONCEBYTES", "crypto_stream_xsalsa20_KEYBYTES", "crypto_stream_xsalsa20_MESSAGEBYTES_MAX", "crypto_stream_xsalsa20_NONCEBYTES", "crypto_verify_16_BYTES", "crypto_verify_32_BYTES", "crypto_verify_64_BYTES"]; for (_3 = 0; _3 < n3.length; _3++) "function" == typeof (c3 = r2["_" + n3[_3].toLowerCase()]) && (e2[n3[_3]] = c3()); var s3 = ["SODIUM_VERSION_STRING", "crypto_pwhash_STRPREFIX", "crypto_pwhash_argon2i_STRPREFIX", "crypto_pwhash_argon2id_STRPREFIX", "crypto_pwhash_scryptsalsa208sha256_STRPREFIX"]; @@ -4052,7 +4052,7 @@ var require_libsodium_wrappers = __commonJS({ var n2 = y(t2, e3); return g(a3), n2; } - function _a(e3, a3, t2) { + function _a2(e3, a3, t2) { var _2 = []; l(t2), e3 = E(_2, e3, "x"); var n2, s2 = 0 | r2._crypto_core_ristretto255_scalarbytes(); @@ -8511,7 +8511,7 @@ var require_lodash = __commonJS({ var nativeKeys = overArg(Object.keys, Object); var nativeMax = Math.max; function arrayLikeKeys(value, inherited) { - var result = isArray3(value) || isArguments(value) ? baseTimes(value.length, String) : []; + var result = isArray4(value) || isArguments(value) ? baseTimes(value.length, String) : []; var length = result.length, skipIndexes = !!length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && (key == "length" || isIndex(key, length)))) { @@ -8552,7 +8552,7 @@ var require_lodash = __commonJS({ function isArguments(value) { return isArrayLikeObject(value) && hasOwnProperty.call(value, "callee") && (!propertyIsEnumerable.call(value, "callee") || objectToString.call(value) == argsTag); } - var isArray3 = Array.isArray; + var isArray4 = Array.isArray; function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } @@ -8574,7 +8574,7 @@ var require_lodash = __commonJS({ return !!value && typeof value == "object"; } function isString(value) { - return typeof value == "string" || !isArray3(value) && isObjectLike(value) && objectToString.call(value) == stringTag; + return typeof value == "string" || !isArray4(value) && isObjectLike(value) && objectToString.call(value) == stringTag; } function isSymbol(value) { return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag; @@ -8768,12 +8768,12 @@ var require_lodash6 = __commonJS({ var stringTag = "[object String]"; var objectProto = Object.prototype; var objectToString = objectProto.toString; - var isArray3 = Array.isArray; + var isArray4 = Array.isArray; function isObjectLike(value) { return !!value && typeof value == "object"; } function isString(value) { - return typeof value == "string" || !isArray3(value) && isObjectLike(value) && objectToString.call(value) == stringTag; + return typeof value == "string" || !isArray4(value) && isObjectLike(value) && objectToString.call(value) == stringTag; } module2.exports = isString; } @@ -9466,6 +9466,1899 @@ function logging() { return cachedLogging; } +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/tslib.mjs +function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") + throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; +} +function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/uuid.mjs +var uuid4 = function() { + const { crypto } = globalThis; + if (crypto?.randomUUID) { + uuid4 = crypto.randomUUID.bind(crypto); + return crypto.randomUUID(); + } + const u8 = new Uint8Array(1); + const randomByte = crypto ? () => crypto.getRandomValues(u8)[0] : () => Math.random() * 255 & 255; + return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16)); +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/errors.mjs +function isAbortError(err) { + return typeof err === "object" && err !== null && // Spec-compliant fetch implementations + ("name" in err && err.name === "AbortError" || // Expo fetch + "message" in err && String(err.message).includes("FetchRequestCanceledException")); +} +var castToError = (err) => { + if (err instanceof Error) + return err; + if (typeof err === "object" && err !== null) { + try { + if (Object.prototype.toString.call(err) === "[object Error]") { + const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); + if (err.stack) + error.stack = err.stack; + if (err.cause && !error.cause) + error.cause = err.cause; + if (err.name) + error.name = err.name; + return error; + } + } catch { + } + try { + return new Error(JSON.stringify(err)); + } catch { + } + } + return new Error(err); +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/core/error.mjs +var StainlessError = class extends Error { +}; +var APIError = class _APIError extends StainlessError { + constructor(status, error, message, headers) { + super(`${_APIError.makeMessage(status, error, message)}`); + this.status = status; + this.headers = headers; + this.error = error; + } + static makeMessage(status, error, message) { + const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message; + if (status && msg) { + return `${status} ${msg}`; + } + if (status) { + return `${status} status code (no body)`; + } + if (msg) { + return msg; + } + return "(no status code or body)"; + } + static generate(status, errorResponse, message, headers) { + if (!status || !headers) { + return new APIConnectionError({ message, cause: castToError(errorResponse) }); + } + const error = errorResponse; + if (status === 400) { + return new BadRequestError(status, error, message, headers); + } + if (status === 401) { + return new AuthenticationError(status, error, message, headers); + } + if (status === 403) { + return new PermissionDeniedError(status, error, message, headers); + } + if (status === 404) { + return new NotFoundError(status, error, message, headers); + } + if (status === 409) { + return new ConflictError(status, error, message, headers); + } + if (status === 422) { + return new UnprocessableEntityError(status, error, message, headers); + } + if (status === 429) { + return new RateLimitError(status, error, message, headers); + } + if (status >= 500) { + return new InternalServerError(status, error, message, headers); + } + return new _APIError(status, error, message, headers); + } +}; +var APIUserAbortError = class extends APIError { + constructor({ message } = {}) { + super(void 0, void 0, message || "Request was aborted.", void 0); + } +}; +var APIConnectionError = class extends APIError { + constructor({ message, cause }) { + super(void 0, void 0, message || "Connection error.", void 0); + if (cause) + this.cause = cause; + } +}; +var APIConnectionTimeoutError = class extends APIConnectionError { + constructor({ message } = {}) { + super({ message: message ?? "Request timed out." }); + } +}; +var BadRequestError = class extends APIError { +}; +var AuthenticationError = class extends APIError { +}; +var PermissionDeniedError = class extends APIError { +}; +var NotFoundError = class extends APIError { +}; +var ConflictError = class extends APIError { +}; +var UnprocessableEntityError = class extends APIError { +}; +var RateLimitError = class extends APIError { +}; +var InternalServerError = class extends APIError { +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/values.mjs +var startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; +var isAbsoluteURL = (url) => { + return startsWithSchemeRegexp.test(url); +}; +var isArray = (val) => (isArray = Array.isArray, isArray(val)); +var isReadonlyArray = isArray; +function maybeObj(x) { + if (typeof x !== "object") { + return {}; + } + return x ?? {}; +} +function isEmptyObj(obj) { + if (!obj) + return true; + for (const _k in obj) + return false; + return true; +} +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +var validatePositiveInteger = (name, n) => { + if (typeof n !== "number" || !Number.isInteger(n)) { + throw new StainlessError(`${name} must be an integer`); + } + if (n < 0) { + throw new StainlessError(`${name} must be a positive integer`); + } + return n; +}; +var safeJSON = (text) => { + try { + return JSON.parse(text); + } catch (err) { + return void 0; + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/sleep.mjs +var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/version.mjs +var VERSION = "0.5.0"; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/detect-platform.mjs +function getDetectedPlatform() { + if (typeof Deno !== "undefined" && Deno.build != null) { + return "deno"; + } + if (typeof EdgeRuntime !== "undefined") { + return "edge"; + } + if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") { + return "node"; + } + return "unknown"; +} +var getPlatformProperties = () => { + const detectedPlatform = getDetectedPlatform(); + if (detectedPlatform === "deno") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": normalizePlatform(Deno.build.os), + "X-Stainless-Arch": normalizeArch(Deno.build.arch), + "X-Stainless-Runtime": "deno", + "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown" + }; + } + if (typeof EdgeRuntime !== "undefined") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": `other:${EdgeRuntime}`, + "X-Stainless-Runtime": "edge", + "X-Stainless-Runtime-Version": globalThis.process.version + }; + } + if (detectedPlatform === "node") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": normalizePlatform(globalThis.process.platform ?? "unknown"), + "X-Stainless-Arch": normalizeArch(globalThis.process.arch ?? "unknown"), + "X-Stainless-Runtime": "node", + "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown" + }; + } + const browserInfo = getBrowserInfo(); + if (browserInfo) { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": "unknown", + "X-Stainless-Runtime": `browser:${browserInfo.browser}`, + "X-Stainless-Runtime-Version": browserInfo.version + }; + } + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": "unknown", + "X-Stainless-Runtime": "unknown", + "X-Stainless-Runtime-Version": "unknown" + }; +}; +function getBrowserInfo() { + if (typeof navigator === "undefined" || !navigator) { + return null; + } + const browserPatterns = [ + { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ } + ]; + for (const { key, pattern } of browserPatterns) { + const match = pattern.exec(navigator.userAgent); + if (match) { + const major = match[1] || 0; + const minor = match[2] || 0; + const patch = match[3] || 0; + return { browser: key, version: `${major}.${minor}.${patch}` }; + } + } + return null; +} +var normalizeArch = (arch) => { + if (arch === "x32") + return "x32"; + if (arch === "x86_64" || arch === "x64") + return "x64"; + if (arch === "arm") + return "arm"; + if (arch === "aarch64" || arch === "arm64") + return "arm64"; + if (arch) + return `other:${arch}`; + return "unknown"; +}; +var normalizePlatform = (platform) => { + platform = platform.toLowerCase(); + if (platform.includes("ios")) + return "iOS"; + if (platform === "android") + return "Android"; + if (platform === "darwin") + return "MacOS"; + if (platform === "win32") + return "Windows"; + if (platform === "freebsd") + return "FreeBSD"; + if (platform === "openbsd") + return "OpenBSD"; + if (platform === "linux") + return "Linux"; + if (platform) + return `Other:${platform}`; + return "Unknown"; +}; +var _platformHeaders; +var getPlatformHeaders = () => { + return _platformHeaders ?? (_platformHeaders = getPlatformProperties()); +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/shims.mjs +function getDefaultFetch() { + if (typeof fetch !== "undefined") { + return fetch; + } + throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Stainless({ fetch })` or polyfill the global, `globalThis.fetch = fetch`"); +} +function makeReadableStream(...args) { + const ReadableStream = globalThis.ReadableStream; + if (typeof ReadableStream === "undefined") { + throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`"); + } + return new ReadableStream(...args); +} +function ReadableStreamFrom(iterable) { + let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); + return makeReadableStream({ + start() { + }, + async pull(controller) { + const { done, value } = await iter.next(); + if (done) { + controller.close(); + } else { + controller.enqueue(value); + } + }, + async cancel() { + await iter.return?.(); + } + }); +} +async function CancelReadableStream(stream) { + if (stream === null || typeof stream !== "object") + return; + if (stream[Symbol.asyncIterator]) { + await stream[Symbol.asyncIterator]().return?.(); + return; + } + const reader = stream.getReader(); + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/request-options.mjs +var FallbackEncoder = ({ headers, body }) => { + return { + bodyHeaders: { + "content-type": "application/json" + }, + body: JSON.stringify(body) + }; +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/qs/formats.mjs +var default_format = "RFC3986"; +var default_formatter = (v) => String(v); +var formatters = { + RFC1738: (v) => String(v).replace(/%20/g, "+"), + RFC3986: default_formatter +}; +var RFC1738 = "RFC1738"; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/qs/utils.mjs +var has = (obj, key) => (has = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has(obj, key)); +var hex_table = /* @__PURE__ */ (() => { + const array = []; + for (let i = 0; i < 256; ++i) { + array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase()); + } + return array; +})(); +var limit = 1024; +var encode = (str, _defaultEncoder, charset, _kind, format) => { + if (str.length === 0) { + return str; + } + let string = str; + if (typeof str === "symbol") { + string = Symbol.prototype.toString.call(str); + } else if (typeof str !== "string") { + string = String(str); + } + if (charset === "iso-8859-1") { + return escape(string).replace(/%u[0-9a-f]{4}/gi, function($0) { + return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; + }); + } + let out = ""; + for (let j = 0; j < string.length; j += limit) { + const segment = string.length >= limit ? string.slice(j, j + limit) : string; + const arr = []; + for (let i = 0; i < segment.length; ++i) { + let c = segment.charCodeAt(i); + if (c === 45 || // - + c === 46 || // . + c === 95 || // _ + c === 126 || // ~ + c >= 48 && c <= 57 || // 0-9 + c >= 65 && c <= 90 || // a-z + c >= 97 && c <= 122 || // A-Z + format === RFC1738 && (c === 40 || c === 41)) { + arr[arr.length] = segment.charAt(i); + continue; + } + if (c < 128) { + arr[arr.length] = hex_table[c]; + continue; + } + if (c < 2048) { + arr[arr.length] = hex_table[192 | c >> 6] + hex_table[128 | c & 63]; + continue; + } + if (c < 55296 || c >= 57344) { + arr[arr.length] = hex_table[224 | c >> 12] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63]; + continue; + } + i += 1; + c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023); + arr[arr.length] = hex_table[240 | c >> 18] + hex_table[128 | c >> 12 & 63] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63]; + } + out += arr.join(""); + } + return out; +}; +function is_buffer(obj) { + if (!obj || typeof obj !== "object") { + return false; + } + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +} +function maybe_map(val, fn) { + if (isArray(val)) { + const mapped = []; + for (let i = 0; i < val.length; i += 1) { + mapped.push(fn(val[i])); + } + return mapped; + } + return fn(val); +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/qs/stringify.mjs +var array_prefix_generators = { + brackets(prefix) { + return String(prefix) + "[]"; + }, + comma: "comma", + indices(prefix, key) { + return String(prefix) + "[" + key + "]"; + }, + repeat(prefix) { + return String(prefix); + } +}; +var push_to_array = function(arr, value_or_array) { + Array.prototype.push.apply(arr, isArray(value_or_array) ? value_or_array : [value_or_array]); +}; +var toISOString; +var defaults = { + addQueryPrefix: false, + allowDots: false, + allowEmptyArrays: false, + arrayFormat: "indices", + charset: "utf-8", + charsetSentinel: false, + delimiter: "&", + encode: true, + encodeDotInKeys: false, + encoder: encode, + encodeValuesOnly: false, + format: default_format, + formatter: default_formatter, + /** @deprecated */ + indices: false, + serializeDate(date) { + return (toISOString ?? (toISOString = Function.prototype.call.bind(Date.prototype.toISOString)))(date); + }, + skipNulls: false, + strictNullHandling: false +}; +function is_non_nullish_primitive(v) { + return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint"; +} +var sentinel = {}; +function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { + let obj = object; + let tmp_sc = sideChannel; + let step = 0; + let find_flag = false; + while ((tmp_sc = tmp_sc.get(sentinel)) !== void 0 && !find_flag) { + const pos = tmp_sc.get(object); + step += 1; + if (typeof pos !== "undefined") { + if (pos === step) { + throw new RangeError("Cyclic object value"); + } else { + find_flag = true; + } + } + if (typeof tmp_sc.get(sentinel) === "undefined") { + step = 0; + } + } + if (typeof filter === "function") { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate?.(obj); + } else if (generateArrayPrefix === "comma" && isArray(obj)) { + obj = maybe_map(obj, function(value) { + if (value instanceof Date) { + return serializeDate?.(value); + } + return value; + }); + } + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? ( + // @ts-expect-error + encoder(prefix, defaults.encoder, charset, "key", format) + ) : prefix; + } + obj = ""; + } + if (is_non_nullish_primitive(obj) || is_buffer(obj)) { + if (encoder) { + const key_value = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, "key", format); + return [ + formatter?.(key_value) + "=" + // @ts-expect-error + formatter?.(encoder(obj, defaults.encoder, charset, "value", format)) + ]; + } + return [formatter?.(prefix) + "=" + formatter?.(String(obj))]; + } + const values = []; + if (typeof obj === "undefined") { + return values; + } + let obj_keys; + if (generateArrayPrefix === "comma" && isArray(obj)) { + if (encodeValuesOnly && encoder) { + obj = maybe_map(obj, encoder); + } + obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; + } else if (isArray(filter)) { + obj_keys = filter; + } else { + const keys = Object.keys(obj); + obj_keys = sort ? keys.sort(sort) : keys; + } + const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix); + const adjusted_prefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix; + if (allowEmptyArrays && isArray(obj) && obj.length === 0) { + return adjusted_prefix + "[]"; + } + for (let j = 0; j < obj_keys.length; ++j) { + const key = obj_keys[j]; + const value = ( + // @ts-ignore + typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key] + ); + if (skipNulls && value === null) { + continue; + } + const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key; + const key_prefix = isArray(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]"); + sideChannel.set(object, step); + const valueSideChannel = /* @__PURE__ */ new WeakMap(); + valueSideChannel.set(sentinel, sideChannel); + push_to_array(values, inner_stringify( + value, + key_prefix, + generateArrayPrefix, + commaRoundTrip, + allowEmptyArrays, + strictNullHandling, + skipNulls, + encodeDotInKeys, + // @ts-ignore + generateArrayPrefix === "comma" && encodeValuesOnly && isArray(obj) ? null : encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + valueSideChannel + )); + } + return values; +} +function normalize_stringify_options(opts = defaults) { + if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") { + throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); + } + if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") { + throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided"); + } + if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") { + throw new TypeError("Encoder has to be a function."); + } + const charset = opts.charset || defaults.charset; + if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { + throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); + } + let format = default_format; + if (typeof opts.format !== "undefined") { + if (!has(formatters, opts.format)) { + throw new TypeError("Unknown format option provided."); + } + format = opts.format; + } + const formatter = formatters[format]; + let filter = defaults.filter; + if (typeof opts.filter === "function" || isArray(opts.filter)) { + filter = opts.filter; + } + let arrayFormat; + if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) { + arrayFormat = opts.arrayFormat; + } else if ("indices" in opts) { + arrayFormat = opts.indices ? "indices" : "repeat"; + } else { + arrayFormat = defaults.arrayFormat; + } + if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") { + throw new TypeError("`commaRoundTrip` must be a boolean, or absent"); + } + const allowDots = typeof opts.allowDots === "undefined" ? !!opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; + return { + addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix, + // @ts-ignore + allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, + arrayFormat, + charset, + charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel, + commaRoundTrip: !!opts.commaRoundTrip, + delimiter: typeof opts.delimiter === "undefined" ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === "boolean" ? opts.encode : defaults.encode, + encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults.encodeDotInKeys, + encoder: typeof opts.encoder === "function" ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter, + format, + formatter, + serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults.skipNulls, + // @ts-ignore + sort: typeof opts.sort === "function" ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling + }; +} +function stringify(object, opts = {}) { + let obj = object; + const options = normalize_stringify_options(opts); + let obj_keys; + let filter; + if (typeof options.filter === "function") { + filter = options.filter; + obj = filter("", obj); + } else if (isArray(options.filter)) { + filter = options.filter; + obj_keys = filter; + } + const keys = []; + if (typeof obj !== "object" || obj === null) { + return ""; + } + const generateArrayPrefix = array_prefix_generators[options.arrayFormat]; + const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip; + if (!obj_keys) { + obj_keys = Object.keys(obj); + } + if (options.sort) { + obj_keys.sort(options.sort); + } + const sideChannel = /* @__PURE__ */ new WeakMap(); + for (let i = 0; i < obj_keys.length; ++i) { + const key = obj_keys[i]; + if (options.skipNulls && obj[key] === null) { + continue; + } + push_to_array(keys, inner_stringify( + obj[key], + key, + // @ts-expect-error + generateArrayPrefix, + commaRoundTrip, + options.allowEmptyArrays, + options.strictNullHandling, + options.skipNulls, + options.encodeDotInKeys, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.format, + options.formatter, + options.encodeValuesOnly, + options.charset, + sideChannel + )); + } + const joined = keys.join(options.delimiter); + let prefix = options.addQueryPrefix === true ? "?" : ""; + if (options.charsetSentinel) { + if (options.charset === "iso-8859-1") { + prefix += "utf8=%26%2310003%3B&"; + } else { + prefix += "utf8=%E2%9C%93&"; + } + } + return joined.length > 0 ? prefix + joined : ""; +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/query.mjs +function stringifyQuery(query) { + return stringify(query, { arrayFormat: "comma" }); +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/log.mjs +var levelNumbers = { + off: 0, + error: 200, + warn: 300, + info: 400, + debug: 500 +}; +var parseLogLevel = (maybeLevel, sourceName, client) => { + if (!maybeLevel) { + return void 0; + } + if (hasOwn(levelNumbers, maybeLevel)) { + return maybeLevel; + } + loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`); + return void 0; +}; +function noop() { +} +function makeLogFn(fnLevel, logger2, logLevel) { + if (!logger2 || levelNumbers[fnLevel] > levelNumbers[logLevel]) { + return noop; + } else { + return logger2[fnLevel].bind(logger2); + } +} +var noopLogger = { + error: noop, + warn: noop, + info: noop, + debug: noop +}; +var cachedLoggers = /* @__PURE__ */ new WeakMap(); +function loggerFor(client) { + const logger2 = client.logger; + const logLevel = client.logLevel ?? "off"; + if (!logger2) { + return noopLogger; + } + const cachedLogger = cachedLoggers.get(logger2); + if (cachedLogger && cachedLogger[0] === logLevel) { + return cachedLogger[1]; + } + const levelLogger = { + error: makeLogFn("error", logger2, logLevel), + warn: makeLogFn("warn", logger2, logLevel), + info: makeLogFn("info", logger2, logLevel), + debug: makeLogFn("debug", logger2, logLevel) + }; + cachedLoggers.set(logger2, [logLevel, levelLogger]); + return levelLogger; +} +var formatRequestDetails = (details) => { + if (details.options) { + details.options = { ...details.options }; + delete details.options["headers"]; + } + if (details.headers) { + details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ + name, + name.toLowerCase() === "authorization" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value + ])); + } + if ("retryOfRequestLogID" in details) { + if (details.retryOfRequestLogID) { + details.retryOf = details.retryOfRequestLogID; + } + delete details.retryOfRequestLogID; + } + return details; +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/parse.mjs +async function defaultParseResponse(client, props) { + const { response, requestLogID, retryOfRequestLogID, startTime } = props; + const body = await (async () => { + if (response.status === 204) { + return null; + } + if (props.options.__binaryResponse) { + return response; + } + const contentType = response.headers.get("content-type"); + const mediaType = contentType?.split(";")[0]?.trim(); + const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json"); + if (isJSON) { + const contentLength = response.headers.get("content-length"); + if (contentLength === "0") { + return void 0; + } + const json = await response.json(); + return json; + } + const text = await response.text(); + return text; + })(); + loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + body, + durationMs: Date.now() - startTime + })); + return body; +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/core/api-promise.mjs +var _APIPromise_client; +var APIPromise = class _APIPromise extends Promise { + constructor(client, responsePromise, parseResponse = defaultParseResponse) { + super((resolve) => { + resolve(null); + }); + this.responsePromise = responsePromise; + this.parseResponse = parseResponse; + _APIPromise_client.set(this, void 0); + __classPrivateFieldSet(this, _APIPromise_client, client, "f"); + } + _thenUnwrap(transform) { + return new _APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => transform(await this.parseResponse(client, props), props)); + } + /** + * Gets the raw `Response` instance instead of parsing the response + * data. + * + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + asResponse() { + return this.responsePromise.then((p) => p.response); + } + /** + * Gets the parsed response data and the raw `Response` instance. + * + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + async withResponse() { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { data, response }; + } + parse() { + if (!this.parsedPromise) { + this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data)); + } + return this.parsedPromise; + } + then(onfulfilled, onrejected) { + return this.parse().then(onfulfilled, onrejected); + } + catch(onrejected) { + return this.parse().catch(onrejected); + } + finally(onfinally) { + return this.parse().finally(onfinally); + } +}; +_APIPromise_client = /* @__PURE__ */ new WeakMap(); + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/core/pagination.mjs +var _AbstractPage_client; +var AbstractPage = class { + constructor(client, response, body, options) { + _AbstractPage_client.set(this, void 0); + __classPrivateFieldSet(this, _AbstractPage_client, client, "f"); + this.options = options; + this.response = response; + this.body = body; + } + hasNextPage() { + const items = this.getPaginatedItems(); + if (!items.length) + return false; + return this.nextPageRequestOptions() != null; + } + async getNextPage() { + const nextOptions = this.nextPageRequestOptions(); + if (!nextOptions) { + throw new StainlessError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`."); + } + return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); + } + async *iterPages() { + let page = this; + yield page; + while (page.hasNextPage()) { + page = await page.getNextPage(); + yield page; + } + } + async *[(_AbstractPage_client = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() { + for await (const page of this.iterPages()) { + for (const item of page.getPaginatedItems()) { + yield item; + } + } + } +}; +var PagePromise = class extends APIPromise { + constructor(client, request, Page2) { + super(client, request, async (client2, props) => new Page2(client2, props.response, await defaultParseResponse(client2, props), props.options)); + } + /** + * Allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ + async *[Symbol.asyncIterator]() { + const page = await this; + for await (const item of page) { + yield item; + } + } +}; +var Page = class extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.next_cursor = body.next_cursor || ""; + } + getPaginatedItems() { + return this.data ?? []; + } + nextPageRequestOptions() { + const cursor = this.next_cursor; + if (!cursor) { + return null; + } + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + cursor + } + }; + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/uploads.mjs +var checkFileSupport = () => { + if (typeof File === "undefined") { + const { process: process7 } = globalThis; + const isOldNode = typeof process7?.versions?.node === "string" && parseInt(process7.versions.node.split(".")) < 20; + throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : "")); + } +}; +function makeFile(fileBits, fileName, options) { + checkFileSupport(); + return new File(fileBits, fileName ?? "unknown_file", options); +} +function getName(value) { + return (typeof value === "object" && value !== null && ("name" in value && value.name && String(value.name) || "url" in value && value.url && String(value.url) || "filename" in value && value.filename && String(value.filename) || "path" in value && value.path && String(value.path)) || "").split(/[\\/]/).pop() || void 0; +} +var isAsyncIterable = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function"; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/to-file.mjs +var isBlobLike = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function"; +var isFileLike = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value); +var isResponseLike = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function"; +async function toFile(value, name, options) { + checkFileSupport(); + value = await value; + if (isFileLike(value)) { + if (value instanceof File) { + return value; + } + return makeFile([await value.arrayBuffer()], value.name); + } + if (isResponseLike(value)) { + const blob = await value.blob(); + name || (name = new URL(value.url).pathname.split(/[\\/]/).pop()); + return makeFile(await getBytes(blob), name, options); + } + const parts = await getBytes(value); + name || (name = getName(value)); + if (!options?.type) { + const type = parts.find((part) => typeof part === "object" && "type" in part && part.type); + if (typeof type === "string") { + options = { ...options, type }; + } + } + return makeFile(parts, name, options); +} +async function getBytes(value) { + let parts = []; + if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. + value instanceof ArrayBuffer) { + parts.push(value); + } else if (isBlobLike(value)) { + parts.push(value instanceof Blob ? value : await value.arrayBuffer()); + } else if (isAsyncIterable(value)) { + for await (const chunk of value) { + parts.push(...await getBytes(chunk)); + } + } else { + const constructor = value?.constructor?.name; + throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError(value)}`); + } + return parts; +} +function propsForError(value) { + if (typeof value !== "object" || value === null) + return ""; + const props = Object.getOwnPropertyNames(value); + return `; props: [${props.map((p) => `"${p}"`).join(", ")}]`; +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/core/resource.mjs +var APIResource = class { + constructor(client) { + this._client = client; + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/path.mjs +function encodeURIPath(str) { + return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); +} +var EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); +var createPathTagFunction = (pathEncoder = encodeURIPath) => function path7(statics, ...params) { + if (statics.length === 1) + return statics[0]; + let postPath = false; + const invalidSegments = []; + const path8 = statics.reduce((previousValue, currentValue, index) => { + if (/[?#]/.test(currentValue)) { + postPath = true; + } + const value = params[index]; + let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value); + if (index !== params.length && (value == null || typeof value === "object" && // handle values from other realms + value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY)?.toString)) { + encoded = value + ""; + invalidSegments.push({ + start: previousValue.length + currentValue.length, + length: encoded.length, + error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter` + }); + } + return previousValue + currentValue + (index === params.length ? "" : encoded); + }, ""); + const pathOnly = path8.split(/[?#]/, 1)[0]; + const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; + let match; + while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) { + invalidSegments.push({ + start: match.index, + length: match[0].length, + error: `Value "${match[0]}" can't be safely passed as a path parameter` + }); + } + invalidSegments.sort((a, b) => a.start - b.start); + if (invalidSegments.length > 0) { + let lastEnd = 0; + const underline = invalidSegments.reduce((acc, segment) => { + const spaces = " ".repeat(segment.start - lastEnd); + const arrows = "^".repeat(segment.length); + lastEnd = segment.start + segment.length; + return acc + spaces + arrows; + }, ""); + throw new StainlessError(`Path parameters result in path with invalid segments: +${invalidSegments.map((e) => e.error).join("\n")} +${path8} +${underline}`); + } + return path8; +}; +var path3 = /* @__PURE__ */ createPathTagFunction(encodeURIPath); + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/builds/diagnostics.mjs +var Diagnostics = class extends APIResource { + /** + * Get the list of diagnostics for a given build. + * + * If no language targets are specified, diagnostics for all languages are + * returned. + */ + list(buildID, query = {}, options) { + return this._client.getAPIList(path3`/v0/builds/${buildID}/diagnostics`, Page, { + query, + ...options + }); + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/builds/target-outputs.mjs +var TargetOutputs = class extends APIResource { + /** + * Retrieve a method to download an output for a given build target. + * + * If the requested type of output is `source`, and the requested output method is + * `url`, a download link to a tarball of the source files is returned. If the + * requested output method is `git`, a Git remote, ref, and access token (if + * necessary) is returned. + * + * Otherwise, the possible types of outputs are specific to the requested target, + * and the output method _must_ be `url`. See the documentation for `type` for more + * information. + */ + retrieve(query, options) { + return this._client.get("/v0/build_target_outputs", { query, ...options }); + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/builds/builds.mjs +var Builds = class extends APIResource { + constructor() { + super(...arguments); + this.diagnostics = new Diagnostics(this._client); + this.targetOutputs = new TargetOutputs(this._client); + } + /** + * Create a build, on top of a project branch, against a given input revision. + * + * The project branch will be modified so that its latest set of config files + * points to the one specified by the input revision. + */ + create(params, options) { + const { project = this._client.project, ...body } = params; + return this._client.post("/v0/builds", { body: { project, ...body }, ...options }); + } + /** + * Retrieve a build by its ID. + */ + retrieve(buildID, options) { + return this._client.get(path3`/v0/builds/${buildID}`, options); + } + /** + * List user-triggered builds for a given project. + * + * An optional revision can be specified to filter by config commit SHA, or hashes + * of file contents. + */ + list(params = {}, options) { + const { project = this._client.project, ...query } = params ?? {}; + return this._client.getAPIList("/v0/builds", Page, { query: { project, ...query }, ...options }); + } + /** + * Create two builds whose outputs can be directly compared with each other. + * + * Created builds _modify_ their project branches so that their latest sets of + * config files point to the ones specified by the input revision. + * + * This endpoint is useful because a build has more inputs than the set of config + * files it uses, so comparing two builds directly may return spurious differences. + * Builds made via this endpoint are guaranteed to have differences arising from + * the set of config files, and any custom code. + */ + compare(params, options) { + const { project = this._client.project, ...body } = params; + return this._client.post("/v0/builds/compare", { body: { project, ...body }, ...options }); + } +}; +Builds.Diagnostics = Diagnostics; +Builds.TargetOutputs = TargetOutputs; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/orgs.mjs +var Orgs = class extends APIResource { + /** + * Retrieve an organization by name. + */ + retrieve(org, options) { + return this._client.get(path3`/v0/orgs/${org}`, options); + } + /** + * List organizations accessible to the current authentication method. + */ + list(options) { + return this._client.get("/v0/orgs", options); + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/projects/branches.mjs +var Branches = class extends APIResource { + /** + * Create a new branch for a project. + * + * The branch inherits the config files from the revision pointed to by the + * `branch_from` parameter. In addition, if the revision is a branch name, the + * branch will also inherit custom code changes from that branch. + */ + create(params, options) { + const { project = this._client.project, ...body } = params; + return this._client.post(path3`/v0/projects/${project}/branches`, { body, ...options }); + } + /** + * Retrieve a project branch by name. + */ + retrieve(branch, params = {}, options) { + const { project = this._client.project } = params ?? {}; + return this._client.get(path3`/v0/projects/${project}/branches/${branch}`, options); + } + /** + * Retrieve a project branch by name. + */ + list(params = {}, options) { + const { project = this._client.project, ...query } = params ?? {}; + return this._client.getAPIList(path3`/v0/projects/${project}/branches`, Page, { + query, + ...options + }); + } + /** + * Delete a project branch by name. + */ + delete(branch, params = {}, options) { + const { project = this._client.project } = params ?? {}; + return this._client.delete(path3`/v0/projects/${project}/branches/${branch}`, options); + } + /** + * Rebase a project branch. + * + * The branch is rebased onto the `base` branch or commit SHA, inheriting any + * config and custom code changes. + */ + rebase(branch, params = {}, options) { + const { project = this._client.project, base } = params ?? {}; + return this._client.put(path3`/v0/projects/${project}/branches/${branch}/rebase`, { + query: { base }, + ...options + }); + } + /** + * Reset a project branch. + * + * If `branch` === `main`, the branch is reset to `target_config_sha`. Otherwise, + * the branch is reset to `main`. + */ + reset(branch, params = {}, options) { + const { project = this._client.project, target_config_sha } = params ?? {}; + return this._client.put(path3`/v0/projects/${project}/branches/${branch}/reset`, { + query: { target_config_sha }, + ...options + }); + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/projects/configs.mjs +var Configs = class extends APIResource { + /** + * Retrieve the configuration files for a given project. + */ + retrieve(params = {}, options) { + const { project = this._client.project, ...query } = params ?? {}; + return this._client.get(path3`/v0/projects/${project}/configs`, { query, ...options }); + } + /** + * Generate suggestions for changes to config files based on an OpenAPI spec. + */ + guess(params, options) { + const { project = this._client.project, ...body } = params; + return this._client.post(path3`/v0/projects/${project}/configs/guess`, { body, ...options }); + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/projects/projects.mjs +var Projects = class extends APIResource { + constructor() { + super(...arguments); + this.branches = new Branches(this._client); + this.configs = new Configs(this._client); + } + /** + * Create a new project. + */ + create(body, options) { + return this._client.post("/v0/projects", { body, ...options }); + } + /** + * Retrieve a project by name. + */ + retrieve(params = {}, options) { + const { project = this._client.project } = params ?? {}; + return this._client.get(path3`/v0/projects/${project}`, options); + } + /** + * Update a project's properties. + */ + update(params = {}, options) { + const { project = this._client.project, ...body } = params ?? {}; + return this._client.patch(path3`/v0/projects/${project}`, { body, ...options }); + } + /** + * List projects in an organization, from oldest to newest. + */ + list(query = {}, options) { + return this._client.getAPIList("/v0/projects", Page, { query, ...options }); + } + /** + * Generates an AI commit message by comparing two git refs in the SDK repository. + */ + generateCommitMessage(params, options) { + const { project = this._client.project, target, ...body } = params; + return this._client.post(path3`/v0/projects/${project}/generate_commit_message`, { + query: { target }, + body, + ...options + }); + } +}; +Projects.Branches = Branches; +Projects.Configs = Configs; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/user.mjs +var User = class extends APIResource { + /** + * Retrieve the currently authenticated user's information. + */ + retrieve(options) { + return this._client.get("/v0/user", options); + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/headers.mjs +var brand_privateNullableHeaders = /* @__PURE__ */ Symbol("brand.privateNullableHeaders"); +function* iterateHeaders(headers) { + if (!headers) + return; + if (brand_privateNullableHeaders in headers) { + const { values, nulls } = headers; + yield* values.entries(); + for (const name of nulls) { + yield [name, null]; + } + return; + } + let shouldClear = false; + let iter; + if (headers instanceof Headers) { + iter = headers.entries(); + } else if (isReadonlyArray(headers)) { + iter = headers; + } else { + shouldClear = true; + iter = Object.entries(headers ?? {}); + } + for (let row of iter) { + const name = row[0]; + if (typeof name !== "string") + throw new TypeError("expected header name to be a string"); + const values = isReadonlyArray(row[1]) ? row[1] : [row[1]]; + let didClear = false; + for (const value of values) { + if (value === void 0) + continue; + if (shouldClear && !didClear) { + didClear = true; + yield [name, null]; + } + yield [name, value]; + } + } +} +var buildHeaders = (newHeaders) => { + const targetHeaders = new Headers(); + const nullHeaders = /* @__PURE__ */ new Set(); + for (const headers of newHeaders) { + const seenHeaders = /* @__PURE__ */ new Set(); + for (const [name, value] of iterateHeaders(headers)) { + const lowerName = name.toLowerCase(); + if (!seenHeaders.has(lowerName)) { + targetHeaders.delete(name); + seenHeaders.add(lowerName); + } + if (value === null) { + targetHeaders.delete(name); + nullHeaders.add(lowerName); + } else { + targetHeaders.append(name, value); + nullHeaders.delete(lowerName); + } + } + } + return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders }; +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/env.mjs +var readEnv = (env) => { + if (typeof globalThis.process !== "undefined") { + return globalThis.process.env?.[env]?.trim() ?? void 0; + } + if (typeof globalThis.Deno !== "undefined") { + return globalThis.Deno.env?.get?.(env)?.trim(); + } + return void 0; +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/lib/unwrap.mjs +async function unwrapFile(value) { + if (value === null) { + return null; + } + if (value.type === "content") { + return value.content; + } + const response = await fetch(value.url); + return response.text(); +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/client.mjs +var _Stainless_instances; +var _a; +var _Stainless_encoder; +var _Stainless_baseURLOverridden; +var environments = { + production: "https://api.stainless.com", + staging: "https://staging.stainless.com" +}; +var Stainless = class { + /** + * API Client for interfacing with the Stainless API. + * + * @param {string | null | undefined} [opts.apiKey=process.env['STAINLESS_API_KEY'] ?? null] + * @param {string | null | undefined} [opts.project] + * @param {Environment} [opts.environment=production] - Specifies the environment URL to use for the API. + * @param {string} [opts.baseURL=process.env['STAINLESS_BASE_URL'] ?? https://api.stainless.com] - Override the default base URL for the API. + * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. + * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. + */ + constructor({ baseURL = readEnv("STAINLESS_BASE_URL"), apiKey = readEnv("STAINLESS_API_KEY") ?? null, project = null, ...opts } = {}) { + _Stainless_instances.add(this); + _Stainless_encoder.set(this, void 0); + this.projects = new Projects(this); + this.builds = new Builds(this); + this.orgs = new Orgs(this); + this.user = new User(this); + const options = { + apiKey, + project, + ...opts, + baseURL, + environment: opts.environment ?? "production" + }; + if (baseURL && opts.environment) { + throw new StainlessError("Ambiguous URL; The `baseURL` option (or STAINLESS_BASE_URL env var) and the `environment` option are given. If you want to use the environment you must pass baseURL: null"); + } + this.baseURL = options.baseURL || environments[options.environment || "production"]; + this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT; + this.logger = options.logger ?? console; + const defaultLogLevel = "warn"; + this.logLevel = defaultLogLevel; + this.logLevel = parseLogLevel(options.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel(readEnv("STAINLESS_LOG"), "process.env['STAINLESS_LOG']", this) ?? defaultLogLevel; + this.fetchOptions = options.fetchOptions; + this.maxRetries = options.maxRetries ?? 2; + this.fetch = options.fetch ?? getDefaultFetch(); + __classPrivateFieldSet(this, _Stainless_encoder, FallbackEncoder, "f"); + this._options = options; + this.apiKey = apiKey; + this.project = project; + } + /** + * Create a new client instance re-using the same options given to the current client with optional overriding. + */ + withOptions(options) { + const client = new this.constructor({ + ...this._options, + environment: options.environment ? options.environment : void 0, + baseURL: options.environment ? void 0 : this.baseURL, + maxRetries: this.maxRetries, + timeout: this.timeout, + logger: this.logger, + logLevel: this.logLevel, + fetch: this.fetch, + fetchOptions: this.fetchOptions, + apiKey: this.apiKey, + project: this.project, + ...options + }); + return client; + } + defaultQuery() { + return this._options.defaultQuery; + } + validateHeaders({ values, nulls }) { + if (this.apiKey && values.get("authorization")) { + return; + } + if (nulls.has("authorization")) { + return; + } + throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "Authorization" headers to be explicitly omitted'); + } + async authHeaders(opts) { + if (this.apiKey == null) { + return void 0; + } + return buildHeaders([{ Authorization: `Bearer ${this.apiKey}` }]); + } + stringifyQuery(query) { + return stringifyQuery(query); + } + getUserAgent() { + return `${this.constructor.name}/JS ${VERSION}`; + } + defaultIdempotencyKey() { + return `stainless-node-retry-${uuid4()}`; + } + makeStatusError(status, error, message, headers) { + return APIError.generate(status, error, message, headers); + } + buildURL(path7, query, defaultBaseURL) { + const baseURL = !__classPrivateFieldGet(this, _Stainless_instances, "m", _Stainless_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL; + const url = isAbsoluteURL(path7) ? new URL(path7) : new URL(baseURL + (baseURL.endsWith("/") && path7.startsWith("/") ? path7.slice(1) : path7)); + const defaultQuery = this.defaultQuery(); + if (!isEmptyObj(defaultQuery)) { + query = { ...defaultQuery, ...query }; + } + if (typeof query === "object" && query && !Array.isArray(query)) { + url.search = this.stringifyQuery(query); + } + return url.toString(); + } + /** + * Used as a callback for mutating the given `FinalRequestOptions` object. + */ + async prepareOptions(options) { + } + /** + * Used as a callback for mutating the given `RequestInit` object. + * + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. + */ + async prepareRequest(request, { url, options }) { + } + get(path7, opts) { + return this.methodRequest("get", path7, opts); + } + post(path7, opts) { + return this.methodRequest("post", path7, opts); + } + patch(path7, opts) { + return this.methodRequest("patch", path7, opts); + } + put(path7, opts) { + return this.methodRequest("put", path7, opts); + } + delete(path7, opts) { + return this.methodRequest("delete", path7, opts); + } + methodRequest(method, path7, opts) { + return this.request(Promise.resolve(opts).then((opts2) => { + return { method, path: path7, ...opts2 }; + })); + } + request(options, remainingRetries = null) { + return new APIPromise(this, this.makeRequest(options, remainingRetries, void 0)); + } + async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { + const options = await optionsInput; + const maxRetries = options.maxRetries ?? this.maxRetries; + if (retriesRemaining == null) { + retriesRemaining = maxRetries; + } + await this.prepareOptions(options); + const { req, url, timeout } = await this.buildRequest(options, { + retryCount: maxRetries - retriesRemaining + }); + await this.prepareRequest(req, { url, options }); + const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0"); + const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`; + const startTime = Date.now(); + loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({ + retryOfRequestLogID, + method: options.method, + url, + options, + headers: req.headers + })); + if (options.signal?.aborted) { + throw new APIUserAbortError(); + } + const controller = new AbortController(); + const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError); + const headersTime = Date.now(); + if (response instanceof globalThis.Error) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + if (options.signal?.aborted) { + throw new APIUserAbortError(); + } + const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : "")); + if (retriesRemaining) { + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`); + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); + } + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`); + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + if (isTimeout) { + throw new APIConnectionTimeoutError(); + } + throw new APIConnectionError({ cause: response }); + } + const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`; + if (!response.ok) { + const shouldRetry = await this.shouldRetry(response); + if (retriesRemaining && shouldRetry) { + const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`; + await CancelReadableStream(response.body); + loggerFor(this).info(`${responseInfo} - ${retryMessage2}`); + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); + } + const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; + loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + const errText = await response.text().catch((err2) => castToError(err2).message); + const errJSON = safeJSON(errText); + const errMessage = errJSON ? void 0 : errText; + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + message: errMessage, + durationMs: Date.now() - startTime + })); + const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); + throw err; + } + loggerFor(this).info(responseInfo); + loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; + } + getAPIList(path7, Page2, opts) { + return this.requestAPIList(Page2, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path7, ...opts2 })) : { method: "get", path: path7, ...opts }); + } + requestAPIList(Page2, options) { + const request = this.makeRequest(options, null, void 0); + return new PagePromise(this, request, Page2); + } + async fetchWithTimeout(url, init, ms, controller) { + const { signal, method, ...options } = init || {}; + const abort = this._makeAbort(controller); + if (signal) + signal.addEventListener("abort", abort, { once: true }); + const timeout = setTimeout(abort, ms); + const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body; + const fetchOptions = { + signal: controller.signal, + ...isReadableBody ? { duplex: "half" } : {}, + method: "GET", + ...options + }; + if (method) { + fetchOptions.method = method.toUpperCase(); + } + try { + return await this.fetch.call(void 0, url, fetchOptions); + } finally { + clearTimeout(timeout); + } + } + async shouldRetry(response) { + const shouldRetryHeader = response.headers.get("x-should-retry"); + if (shouldRetryHeader === "true") + return true; + if (shouldRetryHeader === "false") + return false; + if (response.status === 408) + return true; + if (response.status === 409) + return true; + if (response.status === 429) + return true; + if (response.status >= 500) + return true; + return false; + } + async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { + let timeoutMillis; + const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms"); + if (retryAfterMillisHeader) { + const timeoutMs = parseFloat(retryAfterMillisHeader); + if (!Number.isNaN(timeoutMs)) { + timeoutMillis = timeoutMs; + } + } + const retryAfterHeader = responseHeaders?.get("retry-after"); + if (retryAfterHeader && !timeoutMillis) { + const timeoutSeconds = parseFloat(retryAfterHeader); + if (!Number.isNaN(timeoutSeconds)) { + timeoutMillis = timeoutSeconds * 1e3; + } else { + timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); + } + } + if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1e3)) { + const maxRetries = options.maxRetries ?? this.maxRetries; + timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + } + await sleep(timeoutMillis); + return this.makeRequest(options, retriesRemaining - 1, requestLogID); + } + calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { + const initialRetryDelay = 0.5; + const maxRetryDelay = 8; + const numRetries = maxRetries - retriesRemaining; + const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); + const jitter = 1 - Math.random() * 0.25; + return sleepSeconds * jitter * 1e3; + } + async buildRequest(inputOptions, { retryCount = 0 } = {}) { + const options = { ...inputOptions }; + const { method, path: path7, query, defaultBaseURL } = options; + const url = this.buildURL(path7, query, defaultBaseURL); + if ("timeout" in options) + validatePositiveInteger("timeout", options.timeout); + options.timeout = options.timeout ?? this.timeout; + const { bodyHeaders, body } = this.buildBody({ options }); + const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); + const req = { + method, + headers: reqHeaders, + ...options.signal && { signal: options.signal }, + ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" }, + ...body && { body }, + ...this.fetchOptions ?? {}, + ...options.fetchOptions ?? {} + }; + return { req, url, timeout: options.timeout }; + } + async buildHeaders({ options, method, bodyHeaders, retryCount }) { + let idempotencyHeaders = {}; + if (this.idempotencyHeader && method !== "get") { + if (!options.idempotencyKey) + options.idempotencyKey = this.defaultIdempotencyKey(); + idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; + } + const headers = buildHeaders([ + idempotencyHeaders, + { + Accept: "application/json", + "User-Agent": this.getUserAgent(), + "X-Stainless-Retry-Count": String(retryCount), + ...options.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options.timeout / 1e3)) } : {}, + ...getPlatformHeaders() + }, + await this.authHeaders(options), + this._options.defaultHeaders, + bodyHeaders, + options.headers + ]); + this.validateHeaders(headers); + return headers.values; + } + _makeAbort(controller) { + return () => controller.abort(); + } + buildBody({ options: { body, headers: rawHeaders } }) { + if (!body) { + return { bodyHeaders: void 0, body: void 0 }; + } + const headers = buildHeaders([rawHeaders]); + if ( + // Pass raw type verbatim + ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && // Preserve legacy string encoding behavior for now + headers.values.has("content-type") || // `Blob` is superset of `File` + globalThis.Blob && body instanceof globalThis.Blob || // `FormData` -> `multipart/form-data` + body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded` + body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`) + globalThis.ReadableStream && body instanceof globalThis.ReadableStream + ) { + return { bodyHeaders: void 0, body }; + } else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) { + return { bodyHeaders: void 0, body: ReadableStreamFrom(body) }; + } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") { + return { + bodyHeaders: { "content-type": "application/x-www-form-urlencoded" }, + body: this.stringifyQuery(body) + }; + } else { + return __classPrivateFieldGet(this, _Stainless_encoder, "f").call(this, { body, headers }); + } + } +}; +_a = Stainless, _Stainless_encoder = /* @__PURE__ */ new WeakMap(), _Stainless_instances = /* @__PURE__ */ new WeakSet(), _Stainless_baseURLOverridden = function _Stainless_baseURLOverridden2() { + return this.baseURL !== environments[this._options.environment || "production"]; +}; +Stainless.Stainless = _a; +Stainless.DEFAULT_TIMEOUT = 6e4; +Stainless.StainlessError = StainlessError; +Stainless.APIError = APIError; +Stainless.APIConnectionError = APIConnectionError; +Stainless.APIConnectionTimeoutError = APIConnectionTimeoutError; +Stainless.APIUserAbortError = APIUserAbortError; +Stainless.NotFoundError = NotFoundError; +Stainless.ConflictError = ConflictError; +Stainless.RateLimitError = RateLimitError; +Stainless.BadRequestError = BadRequestError; +Stainless.AuthenticationError = AuthenticationError; +Stainless.InternalServerError = InternalServerError; +Stainless.PermissionDeniedError = PermissionDeniedError; +Stainless.UnprocessableEntityError = UnprocessableEntityError; +Stainless.toFile = toFile; +Stainless.unwrapFile = unwrapFile; +Stainless.Projects = Projects; +Stainless.Builds = Builds; +Stainless.Orgs = Orgs; +Stainless.User = User; + +// src/error.ts +var ActionError = class extends Error { + constructor(message, options) { + super(message, options); + this.name = "ActionError"; + } +}; + // src/logger.ts var LOG_LEVELS = { debug: 0, @@ -9550,11 +11443,14 @@ function createLoggerImpl(logContext) { error: errorFn, fatal(message, ...args) { errorFn(message, ...args); - process.stderr.write( - ` + const isActionError = args.some((arg) => arg instanceof ActionError); + if (!isActionError) { + process.stderr.write( + ` This is a bug. Please report it at ${BUG_REPORT_URL} ` - ); + ); + } }, child(childContext) { const { context, ...rest } = logContext; @@ -9603,9 +11499,9 @@ var import_jsonwebtoken = __toESM(require_jsonwebtoken(), 1); // src/config.ts var fs2 = __toESM(require("node:fs")); var import_node_os = require("node:os"); -var path5 = __toESM(require("node:path")); +var path6 = __toESM(require("node:path")); function getSavedFilePath(file, sha, extension) { - return path5.join( + return path6.join( (0, import_node_os.tmpdir)(), "stainless-generated-config", `${file}-${sha}${extension}` @@ -9627,9 +11523,9 @@ async function saveConfig({ const savedFilePath = getSavedFilePath( "oas", savedSha, - path5.extname(oasPath) + path6.extname(oasPath) ); - fs2.mkdirSync(path5.dirname(savedFilePath), { recursive: true }); + fs2.mkdirSync(path6.dirname(savedFilePath), { recursive: true }); fs2.copyFileSync(oasPath, savedFilePath); fs2.rmSync(oasPath); logger.info(`Saved OAS file to ${savedFilePath}`); @@ -9639,9 +11535,9 @@ async function saveConfig({ const savedFilePath = getSavedFilePath( "config", savedSha, - path5.extname(configPath) + path6.extname(configPath) ); - fs2.mkdirSync(path5.dirname(savedFilePath), { recursive: true }); + fs2.mkdirSync(path6.dirname(savedFilePath), { recursive: true }); fs2.copyFileSync(configPath, savedFilePath); fs2.rmSync(configPath); logger.info(`Saved config file to ${savedFilePath}`); @@ -9708,7 +11604,9 @@ async function getMergeBase({ // src/checkoutPRRef.ts function assertRef(ref) { if (ref !== "base" && ref !== "head") { - throw new Error(`Expected ref to be 'base' or 'head', but was ${ref}`); + throw new ActionError( + `Expected ref to be 'base' or 'head', but was ${ref}` + ); } } async function main() { @@ -9726,7 +11624,7 @@ async function main() { } const { hasOAS, savedSha } = await saveConfig({ oasPath, configPath }); if (!hasOAS) { - throw new Error(`Expected OpenAPI spec at ${oasPath}.`); + throw new ActionError(`Expected OpenAPI spec at ${oasPath}.`); } if (savedSha !== null && savedSha !== mergeBaseSha) { logger.warn( diff --git a/dist/index.js b/dist/index.js index 5189a41..92cddd6 100644 --- a/dist/index.js +++ b/dist/index.js @@ -18420,6 +18420,20 @@ function logging() { return cachedLogging; } +// src/error.ts +var ActionError = class extends Error { + constructor(message, options) { + super(message, options); + this.name = "ActionError"; + } +}; +function maybeToActionError(error) { + if (error instanceof Stainless.BadRequestError || error instanceof Stainless.AuthenticationError || error instanceof Stainless.PermissionDeniedError || error instanceof Stainless.NotFoundError || error instanceof Stainless.UnprocessableEntityError) { + return new ActionError(error.message, { cause: error }); + } + return error; +} + // src/logger.ts var LOG_LEVELS = { debug: 0, @@ -18504,11 +18518,14 @@ function createLoggerImpl(logContext) { error: errorFn, fatal(message, ...args) { errorFn(message, ...args); - process.stderr.write( - ` + const isActionError = args.some((arg) => arg instanceof ActionError); + if (!isActionError) { + process.stderr.write( + ` This is a bug. Please report it at ${BUG_REPORT_URL} ` - ); + ); + } }, child(childContext) { const { context, ...rest } = logContext; @@ -18743,12 +18760,12 @@ async function main() { if (configPath && guessConfig) { const errorMsg = "Can't set both configPath and guessConfig"; logger.error(errorMsg); - throw Error(errorMsg); + throw new ActionError(errorMsg); } if (commitMessage && !isValidConventionalCommitMessage(commitMessage)) { const errorMsg = "Invalid commit message format. Please follow the Conventional Commits format: https://www.conventionalcommits.org/en/v1.0.0/"; logger.error(errorMsg); - throw Error(errorMsg); + throw new ActionError(errorMsg); } if (!projectName) { const stainless = getStainlessClient("index", { @@ -18758,7 +18775,7 @@ async function main() { if (projects.data.length === 0) { const errorMsg = "No projects found. Please create a project first."; logger.error(errorMsg); - throw Error(errorMsg); + throw new ActionError(errorMsg); } projectName = projects.data[0].slug; if (projects.data.length > 1) { @@ -18784,14 +18801,14 @@ async function main() { response.errors )} See more details in the Stainless Studio.`; logger.error(errorMsg); - throw Error(errorMsg); + throw new ActionError(errorMsg); } logger.info("Uploaded!"); if (outputPath) { if (!response.decoratedSpec) { const errorMsg = "Failed to get decorated spec"; logger.error(errorMsg); - throw Error(errorMsg); + throw new ActionError(errorMsg); } if (!(outputPath.endsWith(".yml") || outputPath.endsWith(".yaml"))) { response.decoratedSpec = JSON.stringify( @@ -18876,7 +18893,8 @@ async function uploadSpecAndConfig(specPath, configPath, token, projectName, com return { ok, errors, decoratedSpec }; } if (require.main === module) { - main().catch((err) => { + main().catch((rawErr) => { + const err = maybeToActionError(rawErr); logger.fatal("Fatal error:", err); process.exit(1); }); diff --git a/dist/merge.js b/dist/merge.js index 462376e..a1e75de 100644 --- a/dist/merge.js +++ b/dist/merge.js @@ -9243,135 +9243,37 @@ function logging() { return cachedLogging; } -// src/logger.ts -var LOG_LEVELS = { - debug: 0, - info: 1, - warn: 2, - error: 3, - off: 4 -}; -var COLORS2 = { - reset: "\x1B[0m", - bold: "\x1B[1m", - dim: "\x1B[90m", - cyan: "\x1B[36m", - green: "\x1B[32m", - yellow: "\x1B[33m", - red: "\x1B[31m", - magenta: "\x1B[35m" -}; -var LEVEL_COLORS = { - debug: COLORS2.cyan, - info: COLORS2.green, - warn: COLORS2.yellow, - error: COLORS2.red -}; -var LEVEL_LABELS = { - debug: "DEBUG", - info: "INFO", - warn: "WARN", - error: "ERROR" -}; -var LABEL_WIDTH = 5; -var LOG_LEVEL_CHOICES = ["debug", "info", "warn", "error", "off"]; -function formatTimestamp() { - const now = /* @__PURE__ */ new Date(); - const pad = (n, len = 2) => n.toString().padStart(len, "0"); - return `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}.${pad(now.getMilliseconds(), 3)}`; +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/tslib.mjs +function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") + throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; } -function formatArgs(args) { - if (args.length === 0) return ""; - return args.map((arg) => { - if (arg === null) return "null"; - if (arg === void 0) return "undefined"; - if (typeof arg === "string") return arg; - if (arg instanceof Error) return arg.stack || arg.message; - try { - return JSON.stringify(arg, null, 2); - } catch { - return String(arg); - } - }).join(" "); +function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); } -function createLogFn(level, { context, minLevel, provider }) { - if (LOG_LEVELS[level] < minLevel) { - return () => { - }; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/uuid.mjs +var uuid4 = function() { + const { crypto: crypto2 } = globalThis; + if (crypto2?.randomUUID) { + uuid4 = crypto2.randomUUID.bind(crypto2); + return crypto2.randomUUID(); } - return (message, ...args) => { - const extra = formatArgs(args); - const line = [ - `${COLORS2.dim}${formatTimestamp()}${COLORS2.reset}`, - `${LEVEL_COLORS[level]}${COLORS2.bold}${LEVEL_LABELS[level].padEnd(LABEL_WIDTH)}${COLORS2.reset}`, - context ? `${COLORS2.magenta}[${context}]${COLORS2.reset}` : null, - message, - extra || null - ].filter(Boolean).join(" "); - const stream = level === "error" || level === "warn" ? process.stderr : process.stdout; - stream.write(line + "\n"); - if (level === "error") { - provider.emitErrorAnnotation(message + (extra ? " " + extra : "")); - } - }; -} -var BUG_REPORT_URL = "https://github.com/stainless-api/upload-openapi-spec-action/issues"; -function createLoggerImpl(logContext) { - const { provider } = logContext; - const errorFn = createLogFn("error", logContext); - const groupStack = []; - return { - debug: createLogFn("debug", logContext), - info: createLogFn("info", logContext), - warn: createLogFn("warn", logContext), - error: errorFn, - fatal(message, ...args) { - errorFn(message, ...args); - process.stderr.write( - ` -This is a bug. Please report it at ${BUG_REPORT_URL} -` - ); - }, - child(childContext) { - const { context, ...rest } = logContext; - const newContext = context ? `${context}:${childContext}` : childContext; - return createLoggerImpl({ context: newContext, ...rest }); - }, - group(name) { - const id = provider.startGroup(name); - groupStack.push(id); - }, - groupEnd() { - const id = groupStack.pop(); - if (id !== void 0) { - provider.endGroup(id); - } - }, - withGroup(name, fn) { - const id = provider.startGroup(name); - try { - const result = fn(); - if (result instanceof Promise) { - return result.finally(() => provider.endGroup(id)); - } - provider.endGroup(id); - return result; - } catch (e) { - provider.endGroup(id); - throw e; - } - } - }; -} -function createLogger(options = {}) { - const minLevel = LOG_LEVELS[options.level ?? getInput("log_level", { choices: LOG_LEVEL_CHOICES }) ?? "info"]; - const provider = logging(); - return createLoggerImpl({ minLevel, provider }); -} -var logger = createLogger(); + const u8 = new Uint8Array(1); + const randomByte = crypto2 ? () => crypto2.getRandomValues(u8)[0] : () => Math.random() * 255 & 255; + return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16)); +}; -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/errors.mjs +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/errors.mjs function isAbortError(err) { return typeof err === "object" && err !== null && // Spec-compliant fetch implementations ("name" in err && err.name === "AbortError" || // Expo fetch @@ -9402,13 +9304,10 @@ var castToError = (err) => { return new Error(err); }; -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/core/error.mjs -var GitHubError = /* @__PURE__ */ (() => { - class GitHubError2 extends Error { - } - return GitHubError2; -})(); -var APIError = class _APIError extends GitHubError { +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/core/error.mjs +var StainlessError = class extends Error { +}; +var APIError = class _APIError extends StainlessError { constructor(status, error, message, headers) { super(`${_APIError.makeMessage(status, error, message)}`); this.status = status; @@ -9494,36 +9393,7 @@ var RateLimitError = class extends APIError { var InternalServerError = class extends APIError { }; -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/core/resource.mjs -var APIResource = /* @__PURE__ */ (() => { - class APIResource4 { - constructor(client) { - this._client = client; - } - } - APIResource4._key = []; - return APIResource4; -})(); - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/tslib.mjs -function __classPrivateFieldSet(receiver, state, value, kind, f) { - if (kind === "m") - throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) - throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) - throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; -} -function __classPrivateFieldGet(receiver, state, kind, f) { - if (kind === "a" && !f) - throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) - throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -} - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/utils/values.mjs +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/values.mjs var startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; var isAbsoluteURL = (url) => { return startsWithSchemeRegexp.test(url); @@ -9548,10 +9418,10 @@ function hasOwn(obj, key) { } var validatePositiveInteger = (name, n) => { if (typeof n !== "number" || !Number.isInteger(n)) { - throw new GitHubError(`${name} must be an integer`); + throw new StainlessError(`${name} must be an integer`); } if (n < 0) { - throw new GitHubError(`${name} must be a positive integer`); + throw new StainlessError(`${name} must be a positive integer`); } return n; }; @@ -9563,3963 +9433,2625 @@ var safeJSON = (text) => { } }; -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/utils/log.mjs -var levelNumbers = { - off: 0, - error: 200, - warn: 300, - info: 400, - debug: 500 -}; -var parseLogLevel = (maybeLevel, sourceName, client) => { - if (!maybeLevel) { - return void 0; +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/sleep.mjs +var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/version.mjs +var VERSION = "0.5.0"; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/detect-platform.mjs +function getDetectedPlatform() { + if (typeof Deno !== "undefined" && Deno.build != null) { + return "deno"; } - if (hasOwn(levelNumbers, maybeLevel)) { - return maybeLevel; + if (typeof EdgeRuntime !== "undefined") { + return "edge"; } - loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`); - return void 0; -}; -function noop() { -} -function makeLogFn(fnLevel, logger2, logLevel) { - if (!logger2 || levelNumbers[fnLevel] > levelNumbers[logLevel]) { - return noop; - } else { - return logger2[fnLevel].bind(logger2); + if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") { + return "node"; } + return "unknown"; } -var noopLogger = { - error: noop, - warn: noop, - info: noop, - debug: noop -}; -var cachedLoggers = /* @__PURE__ */ new WeakMap(); -function loggerFor(client) { - const logger2 = client.logger; - const logLevel = client.logLevel ?? "off"; - if (!logger2) { - return noopLogger; +var getPlatformProperties = () => { + const detectedPlatform = getDetectedPlatform(); + if (detectedPlatform === "deno") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": normalizePlatform(Deno.build.os), + "X-Stainless-Arch": normalizeArch(Deno.build.arch), + "X-Stainless-Runtime": "deno", + "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown" + }; } - const cachedLogger = cachedLoggers.get(logger2); - if (cachedLogger && cachedLogger[0] === logLevel) { - return cachedLogger[1]; + if (typeof EdgeRuntime !== "undefined") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": `other:${EdgeRuntime}`, + "X-Stainless-Runtime": "edge", + "X-Stainless-Runtime-Version": globalThis.process.version + }; } - const levelLogger = { - error: makeLogFn("error", logger2, logLevel), - warn: makeLogFn("warn", logger2, logLevel), - info: makeLogFn("info", logger2, logLevel), - debug: makeLogFn("debug", logger2, logLevel) - }; - cachedLoggers.set(logger2, [logLevel, levelLogger]); - return levelLogger; -} -var formatRequestDetails = (details) => { - if (details.options) { - details.options = { ...details.options }; - delete details.options["headers"]; + if (detectedPlatform === "node") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": normalizePlatform(globalThis.process.platform ?? "unknown"), + "X-Stainless-Arch": normalizeArch(globalThis.process.arch ?? "unknown"), + "X-Stainless-Runtime": "node", + "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown" + }; } - if (details.headers) { - details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ - name, - name.toLowerCase() === "authorization" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value - ])); + const browserInfo = getBrowserInfo(); + if (browserInfo) { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": "unknown", + "X-Stainless-Runtime": `browser:${browserInfo.browser}`, + "X-Stainless-Runtime-Version": browserInfo.version + }; } - if ("retryOfRequestLogID" in details) { - if (details.retryOfRequestLogID) { - details.retryOf = details.retryOfRequestLogID; + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": "unknown", + "X-Stainless-Runtime": "unknown", + "X-Stainless-Runtime-Version": "unknown" + }; +}; +function getBrowserInfo() { + if (typeof navigator === "undefined" || !navigator) { + return null; + } + const browserPatterns = [ + { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ } + ]; + for (const { key, pattern } of browserPatterns) { + const match = pattern.exec(navigator.userAgent); + if (match) { + const major = match[1] || 0; + const minor = match[2] || 0; + const patch = match[3] || 0; + return { browser: key, version: `${major}.${minor}.${patch}` }; } - delete details.retryOfRequestLogID; } - return details; + return null; +} +var normalizeArch = (arch) => { + if (arch === "x32") + return "x32"; + if (arch === "x86_64" || arch === "x64") + return "x64"; + if (arch === "arm") + return "arm"; + if (arch === "aarch64" || arch === "arm64") + return "arm64"; + if (arch) + return `other:${arch}`; + return "unknown"; +}; +var normalizePlatform = (platform) => { + platform = platform.toLowerCase(); + if (platform.includes("ios")) + return "iOS"; + if (platform === "android") + return "Android"; + if (platform === "darwin") + return "MacOS"; + if (platform === "win32") + return "Windows"; + if (platform === "freebsd") + return "FreeBSD"; + if (platform === "openbsd") + return "OpenBSD"; + if (platform === "linux") + return "Linux"; + if (platform) + return `Other:${platform}`; + return "Unknown"; +}; +var _platformHeaders; +var getPlatformHeaders = () => { + return _platformHeaders ?? (_platformHeaders = getPlatformProperties()); }; -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/parse.mjs -async function defaultParseResponse(client, props) { - const { response, requestLogID, retryOfRequestLogID, startTime } = props; - const body = await (async () => { - if (response.status === 204) { - return null; - } - if (props.options.__binaryResponse) { - return response; - } - const contentType = response.headers.get("content-type"); - const mediaType = contentType?.split(";")[0]?.trim(); - const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json"); - if (isJSON) { - const contentLength = response.headers.get("content-length"); - if (contentLength === "0") { - return void 0; - } - const json = await response.json(); - return json; - } - const text = await response.text(); - return text; - })(); - loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - body, - durationMs: Date.now() - startTime - })); - return body; +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/shims.mjs +function getDefaultFetch() { + if (typeof fetch !== "undefined") { + return fetch; + } + throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Stainless({ fetch })` or polyfill the global, `globalThis.fetch = fetch`"); } - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/core/api-promise.mjs -var _APIPromise_client; -var APIPromise = /* @__PURE__ */ (() => { - class APIPromise4 extends Promise { - constructor(client, responsePromise, parseResponse = defaultParseResponse) { - super((resolve) => { - resolve(null); - }); - this.responsePromise = responsePromise; - this.parseResponse = parseResponse; - _APIPromise_client.set(this, void 0); - __classPrivateFieldSet(this, _APIPromise_client, client, "f"); - } - _thenUnwrap(transform) { - return new APIPromise4(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => transform(await this.parseResponse(client, props), props)); - } - /** - * Gets the raw `Response` instance instead of parsing the response - * data. - * - * If you want to parse the response body but still get the `Response` - * instance, you can use {@link withResponse()}. - * - * 👋 Getting the wrong TypeScript type for `Response`? - * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` - * to your `tsconfig.json`. - */ - asResponse() { - return this.responsePromise.then((p) => p.response); - } - /** - * Gets the parsed response data and the raw `Response` instance. - * - * If you just want to get the raw `Response` instance without parsing it, - * you can use {@link asResponse()}. - * - * 👋 Getting the wrong TypeScript type for `Response`? - * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` - * to your `tsconfig.json`. - */ - async withResponse() { - const [data, response] = await Promise.all([this.parse(), this.asResponse()]); - return { data, response }; - } - parse() { - if (!this.parsedPromise) { - this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data)); +function makeReadableStream(...args) { + const ReadableStream = globalThis.ReadableStream; + if (typeof ReadableStream === "undefined") { + throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`"); + } + return new ReadableStream(...args); +} +function ReadableStreamFrom(iterable) { + let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); + return makeReadableStream({ + start() { + }, + async pull(controller) { + const { done, value } = await iter.next(); + if (done) { + controller.close(); + } else { + controller.enqueue(value); } - return this.parsedPromise; - } - then(onfulfilled, onrejected) { - return this.parse().then(onfulfilled, onrejected); - } - catch(onrejected) { - return this.parse().catch(onrejected); - } - finally(onfinally) { - return this.parse().finally(onfinally); + }, + async cancel() { + await iter.return?.(); } + }); +} +async function CancelReadableStream(stream) { + if (stream === null || typeof stream !== "object") + return; + if (stream[Symbol.asyncIterator]) { + await stream[Symbol.asyncIterator]().return?.(); + return; } - _APIPromise_client = /* @__PURE__ */ new WeakMap(); - return APIPromise4; -})(); + const reader = stream.getReader(); + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; +} -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/core/pagination.mjs -var _AbstractPage_client; -var AbstractPage = /* @__PURE__ */ (() => { - class AbstractPage3 { - constructor(client, response, body, options) { - _AbstractPage_client.set(this, void 0); - __classPrivateFieldSet(this, _AbstractPage_client, client, "f"); - this.options = options; - this.response = response; - this.body = body; - } - hasNextPage() { - const items = this.getPaginatedItems(); - if (!items.length) - return false; - return this.nextPageRequestOptions() != null; - } - async getNextPage() { - const nextOptions = this.nextPageRequestOptions(); - if (!nextOptions) { - throw new GitHubError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`."); +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/request-options.mjs +var FallbackEncoder = ({ headers, body }) => { + return { + bodyHeaders: { + "content-type": "application/json" + }, + body: JSON.stringify(body) + }; +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/qs/formats.mjs +var default_format = "RFC3986"; +var default_formatter = (v) => String(v); +var formatters = { + RFC1738: (v) => String(v).replace(/%20/g, "+"), + RFC3986: default_formatter +}; +var RFC1738 = "RFC1738"; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/qs/utils.mjs +var has = (obj, key) => (has = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has(obj, key)); +var hex_table = /* @__PURE__ */ (() => { + const array = []; + for (let i = 0; i < 256; ++i) { + array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase()); + } + return array; +})(); +var limit = 1024; +var encode = (str, _defaultEncoder, charset, _kind, format) => { + if (str.length === 0) { + return str; + } + let string = str; + if (typeof str === "symbol") { + string = Symbol.prototype.toString.call(str); + } else if (typeof str !== "string") { + string = String(str); + } + if (charset === "iso-8859-1") { + return escape(string).replace(/%u[0-9a-f]{4}/gi, function($0) { + return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; + }); + } + let out = ""; + for (let j = 0; j < string.length; j += limit) { + const segment = string.length >= limit ? string.slice(j, j + limit) : string; + const arr = []; + for (let i = 0; i < segment.length; ++i) { + let c = segment.charCodeAt(i); + if (c === 45 || // - + c === 46 || // . + c === 95 || // _ + c === 126 || // ~ + c >= 48 && c <= 57 || // 0-9 + c >= 65 && c <= 90 || // a-z + c >= 97 && c <= 122 || // A-Z + format === RFC1738 && (c === 40 || c === 41)) { + arr[arr.length] = segment.charAt(i); + continue; } - return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); - } - async *iterPages() { - let page = this; - yield page; - while (page.hasNextPage()) { - page = await page.getNextPage(); - yield page; + if (c < 128) { + arr[arr.length] = hex_table[c]; + continue; } - } - async *[(_AbstractPage_client = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() { - for await (const page of this.iterPages()) { - for (const item of page.getPaginatedItems()) { - yield item; - } + if (c < 2048) { + arr[arr.length] = hex_table[192 | c >> 6] + hex_table[128 | c & 63]; + continue; } - } - } - return AbstractPage3; -})(); -var PagePromise = /* @__PURE__ */ (() => { - class PagePromise3 extends APIPromise { - constructor(client, request, Page2) { - super(client, request, async (client2, props) => new Page2(client2, props.response, await defaultParseResponse(client2, props), props.options)); - } - /** - * Allow auto-paginating iteration on an unawaited list call, eg: - * - * for await (const item of client.items.list()) { - * console.log(item) - * } - */ - async *[Symbol.asyncIterator]() { - const page = await this; - for await (const item of page) { - yield item; + if (c < 55296 || c >= 57344) { + arr[arr.length] = hex_table[224 | c >> 12] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63]; + continue; } + i += 1; + c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023); + arr[arr.length] = hex_table[240 | c >> 18] + hex_table[128 | c >> 12 & 63] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63]; } + out += arr.join(""); } - return PagePromise3; -})(); -var NumberedPage = class extends AbstractPage { - constructor(client, response, body, options) { - super(client, response, body, options); - this.data = body || []; + return out; +}; +function is_buffer(obj) { + if (!obj || typeof obj !== "object") { + return false; } - getPaginatedItems() { - return this.data ?? []; + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +} +function maybe_map(val, fn) { + if (isArray(val)) { + const mapped = []; + for (let i = 0; i < val.length; i += 1) { + mapped.push(fn(val[i])); + } + return mapped; } - nextPageRequestOptions() { - const query = this.options.query; - const currentPage = query?.page ?? 1; - return { - ...this.options, - query: { - ...maybeObj(this.options.query), - page: currentPage + 1 - } - }; + return fn(val); +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/qs/stringify.mjs +var array_prefix_generators = { + brackets(prefix) { + return String(prefix) + "[]"; + }, + comma: "comma", + indices(prefix, key) { + return String(prefix) + "[" + key + "]"; + }, + repeat(prefix) { + return String(prefix); } }; - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/utils/path.mjs -function encodeURIPath(str) { - return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); +var push_to_array = function(arr, value_or_array) { + Array.prototype.push.apply(arr, isArray(value_or_array) ? value_or_array : [value_or_array]); +}; +var toISOString; +var defaults = { + addQueryPrefix: false, + allowDots: false, + allowEmptyArrays: false, + arrayFormat: "indices", + charset: "utf-8", + charsetSentinel: false, + delimiter: "&", + encode: true, + encodeDotInKeys: false, + encoder: encode, + encodeValuesOnly: false, + format: default_format, + formatter: default_formatter, + /** @deprecated */ + indices: false, + serializeDate(date) { + return (toISOString ?? (toISOString = Function.prototype.call.bind(Date.prototype.toISOString)))(date); + }, + skipNulls: false, + strictNullHandling: false +}; +function is_non_nullish_primitive(v) { + return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint"; } -var EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); -var createPathTagFunction = (pathEncoder = encodeURIPath) => function path7(statics, ...params) { - if (statics.length === 1) - return statics[0]; - let postPath = false; - const invalidSegments = []; - const path8 = statics.reduce((previousValue, currentValue, index) => { - if (/[?#]/.test(currentValue)) { - postPath = true; +var sentinel = {}; +function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { + let obj = object; + let tmp_sc = sideChannel; + let step = 0; + let find_flag = false; + while ((tmp_sc = tmp_sc.get(sentinel)) !== void 0 && !find_flag) { + const pos = tmp_sc.get(object); + step += 1; + if (typeof pos !== "undefined") { + if (pos === step) { + throw new RangeError("Cyclic object value"); + } else { + find_flag = true; + } } - const value = params[index]; - let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value); - if (index !== params.length && (value == null || typeof value === "object" && // handle values from other realms - value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY)?.toString)) { - encoded = value + ""; - invalidSegments.push({ - start: previousValue.length + currentValue.length, - length: encoded.length, - error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter` - }); + if (typeof tmp_sc.get(sentinel) === "undefined") { + step = 0; } - return previousValue + currentValue + (index === params.length ? "" : encoded); - }, ""); - const pathOnly = path8.split(/[?#]/, 1)[0]; - const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; - let match; - while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) { - invalidSegments.push({ - start: match.index, - length: match[0].length, - error: `Value "${match[0]}" can't be safely passed as a path parameter` - }); } - invalidSegments.sort((a, b) => a.start - b.start); - if (invalidSegments.length > 0) { - let lastEnd = 0; - const underline = invalidSegments.reduce((acc, segment) => { - const spaces = " ".repeat(segment.start - lastEnd); - const arrows = "^".repeat(segment.length); - lastEnd = segment.start + segment.length; - return acc + spaces + arrows; - }, ""); - throw new GitHubError(`Path parameters result in path with invalid segments: -${invalidSegments.map((e) => e.error).join("\n")} -${path8} -${underline}`); + if (typeof filter === "function") { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate?.(obj); + } else if (generateArrayPrefix === "comma" && isArray(obj)) { + obj = maybe_map(obj, function(value) { + if (value instanceof Date) { + return serializeDate?.(value); + } + return value; + }); } - return path8; -}; -var path = /* @__PURE__ */ createPathTagFunction(encodeURIPath); - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/resources/repos/commits/commits.mjs -var BaseCommits = /* @__PURE__ */ (() => { - class BaseCommits4 extends APIResource { - /** - * Returns the contents of a single commit reference. You must have `read` access - * for the repository to use this endpoint. - * - * > [!NOTE] If there are more than 300 files in the commit diff and the default - * > JSON media type is requested, the response will include pagination link - * > headers for the remaining files, up to a limit of 3000 files. Each page - * > contains the static commit information, and the only changes are to the file - * > listing. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * Pagination query parameters are not supported for these media types. - * - * - **`application/vnd.github.diff`**: Returns the diff of the commit. Larger - * diffs may time out and return a 5xx status code. - * - **`application/vnd.github.patch`**: Returns the patch of the commit. Diffs - * with binary data will have no `patch` property. Larger diffs may time out and - * return a 5xx status code. - * - **`application/vnd.github.sha`**: Returns the commit's SHA-1 hash. You can use - * this endpoint to check if a remote reference's SHA-1 hash is the same as your - * local reference's SHA-1 hash by providing the local SHA-1 reference as the - * ETag. - * - * **Signature verification object** - * - * The response will include a `verification` object that describes the result of - * verifying the commit's signature. The following fields are included in the - * `verification` object: - * - * | Name | Type | Description | - * | ------------- | --------- | ------------------------------------------------------------------------------------------------ | - * | `verified` | `boolean` | Indicates whether GitHub considers the signature in this commit to be verified. | - * | `reason` | `string` | The reason for verified value. Possible values and their meanings are enumerated in table below. | - * | `signature` | `string` | The signature that was extracted from the commit. | - * | `payload` | `string` | The value that was signed. | - * | `verified_at` | `string` | The date the signature was verified by GitHub. | - * - * These are the possible values for `reason` in the `verification` object: - * - * | Value | Description | - * | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------- | - * | `expired_key` | The key that made the signature is expired. | - * | `not_signing_key` | The "signing" flag is not among the usage flags in the GPG key that made the signature. | - * | `gpgverify_error` | There was an error communicating with the signature verification service. | - * | `gpgverify_unavailable` | The signature verification service is currently unavailable. | - * | `unsigned` | The object does not include a signature. | - * | `unknown_signature_type` | A non-PGP signature was found in the commit. | - * | `no_user` | No user was associated with the `committer` email address in the commit. | - * | `unverified_email` | The `committer` email address in the commit was associated with a user, but the email address is not verified on their account. | - * | `bad_email` | The `committer` email address in the commit is not included in the identities of the PGP key that made the signature. | - * | `unknown_key` | The key that made the signature has not been registered with any user's account. | - * | `malformed_signature` | There was an error parsing the signature. | - * | `invalid` | The signature could not be cryptographically verified using the key whose key-id was found in the signature. | - * | `valid` | None of the above errors applied, so the signature is considered to be verified. | - * - * @example - * ```ts - * const commit = await client.repos.commits.retrieve('ref', { - * owner: 'owner', - * repo: 'repo', - * }); - * ``` - */ - retrieve(ref, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/commits/${ref}`, { query, ...options }); - } - /** - * **Signature verification object** - * - * The response will include a `verification` object that describes the result of - * verifying the commit's signature. The following fields are included in the - * `verification` object: - * - * | Name | Type | Description | - * | ------------- | --------- | ------------------------------------------------------------------------------------------------ | - * | `verified` | `boolean` | Indicates whether GitHub considers the signature in this commit to be verified. | - * | `reason` | `string` | The reason for verified value. Possible values and their meanings are enumerated in table below. | - * | `signature` | `string` | The signature that was extracted from the commit. | - * | `payload` | `string` | The value that was signed. | - * | `verified_at` | `string` | The date the signature was verified by GitHub. | - * - * These are the possible values for `reason` in the `verification` object: - * - * | Value | Description | - * | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------- | - * | `expired_key` | The key that made the signature is expired. | - * | `not_signing_key` | The "signing" flag is not among the usage flags in the GPG key that made the signature. | - * | `gpgverify_error` | There was an error communicating with the signature verification service. | - * | `gpgverify_unavailable` | The signature verification service is currently unavailable. | - * | `unsigned` | The object does not include a signature. | - * | `unknown_signature_type` | A non-PGP signature was found in the commit. | - * | `no_user` | No user was associated with the `committer` email address in the commit. | - * | `unverified_email` | The `committer` email address in the commit was associated with a user, but the email address is not verified on their account. | - * | `bad_email` | The `committer` email address in the commit is not included in the identities of the PGP key that made the signature. | - * | `unknown_key` | The key that made the signature has not been registered with any user's account. | - * | `malformed_signature` | There was an error parsing the signature. | - * | `invalid` | The signature could not be cryptographically verified using the key whose key-id was found in the signature. | - * | `valid` | None of the above errors applied, so the signature is considered to be verified. | - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const commit of client.repos.commits.list({ - * owner: 'owner', - * repo: 'repo', - * })) { - * // ... - * } - * ``` - */ - list(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.getAPIList(path`/repos/${owner}/${repo}/commits`, NumberedPage, { - query, - ...options - }); + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? ( + // @ts-expect-error + encoder(prefix, defaults.encoder, charset, "key", format) + ) : prefix; } - /** - * Protected branches are available in public repositories with GitHub Free and - * GitHub Free for organizations, and in public and private repositories with - * GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. - * For more information, see - * [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) - * in the GitHub Help documentation. - * - * Returns all branches where the given commit SHA is the HEAD, or latest commit - * for the branch. - * - * @example - * ```ts - * const response = - * await client.repos.commits.listBranchesWhereHead( - * 'commit_sha', - * { owner: 'owner', repo: 'repo' }, - * ); - * ``` - */ - listBranchesWhereHead(commitSha, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/commits/${commitSha}/branches-where-head`, options); + obj = ""; + } + if (is_non_nullish_primitive(obj) || is_buffer(obj)) { + if (encoder) { + const key_value = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, "key", format); + return [ + formatter?.(key_value) + "=" + // @ts-expect-error + formatter?.(encoder(obj, defaults.encoder, charset, "value", format)) + ]; } - /** - * Lists check runs for a commit ref. The `ref` can be a SHA, branch name, or a tag - * name. - * - * > [!NOTE] The endpoints to manage checks only look for pushes in the repository - * > where the check suite or check run were created. Pushes to a branch in a - * > forked repository are not detected and return an empty `pull_requests` array. - * - * If there are more than 1000 check suites on a single git reference, this - * endpoint will limit check runs to the 1000 most recent check suites. To iterate - * over all possible check runs, use the - * [List check suites for a Git reference](https://docs.github.com/rest/reference/checks#list-check-suites-for-a-git-reference) - * endpoint and provide the `check_suite_id` parameter to the - * [List check runs in a check suite](https://docs.github.com/rest/reference/checks#list-check-runs-in-a-check-suite) - * endpoint. - * - * OAuth app tokens and personal access tokens (classic) need the `repo` scope to - * use this endpoint on a private repository. - * - * @example - * ```ts - * const response = await client.repos.commits.listCheckRuns( - * 'ref', - * { owner: 'owner', repo: 'repo' }, - * ); - * ``` - */ - listCheckRuns(ref, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/commits/${ref}/check-runs`, { query, ...options }); + return [formatter?.(prefix) + "=" + formatter?.(String(obj))]; + } + const values = []; + if (typeof obj === "undefined") { + return values; + } + let obj_keys; + if (generateArrayPrefix === "comma" && isArray(obj)) { + if (encodeValuesOnly && encoder) { + obj = maybe_map(obj, encoder); } - /** - * Lists check suites for a commit `ref`. The `ref` can be a SHA, branch name, or a - * tag name. - * - * > [!NOTE] The endpoints to manage checks only look for pushes in the repository - * > where the check suite or check run were created. Pushes to a branch in a - * > forked repository are not detected and return an empty `pull_requests` array - * > and a `null` value for `head_branch`. - * - * OAuth app tokens and personal access tokens (classic) need the `repo` scope to - * use this endpoint on a private repository. - * - * @example - * ```ts - * const response = await client.repos.commits.listCheckSuites( - * 'ref', - * { owner: 'owner', repo: 'repo' }, - * ); - * ``` - */ - listCheckSuites(ref, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/commits/${ref}/check-suites`, { query, ...options }); - } - /** - * Lists the merged pull request that introduced the commit to the repository. If - * the commit is not present in the default branch, it will return merged and open - * pull requests associated with the commit. - * - * To list the open or merged pull requests associated with a branch, you can set - * the `commit_sha` parameter to the branch name. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const pullRequestSimple of client.repos.commits.listPullRequests( - * 'commit_sha', - * { owner: 'owner', repo: 'repo' }, - * )) { - * // ... - * } - * ``` - */ - listPullRequests(commitSha, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.getAPIList(path`/repos/${owner}/${repo}/commits/${commitSha}/pulls`, NumberedPage, { query, ...options }); - } - /** - * Users with pull access in a repository can view commit statuses for a given ref. - * The ref can be a SHA, a branch name, or a tag name. Statuses are returned in - * reverse chronological order. The first status in the list will be the latest - * one. - * - * This resource is also available via a legacy route: - * `GET /repos/:owner/:repo/statuses/:ref`. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const commitListStatusesResponse of client.repos.commits.listStatuses( - * 'ref', - * { owner: 'owner', repo: 'repo' }, - * )) { - * // ... - * } - * ``` - */ - listStatuses(ref, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.getAPIList(path`/repos/${owner}/${repo}/commits/${ref}/statuses`, NumberedPage, { query, ...options }); - } - /** - * Users with pull access in a repository can access a combined view of commit - * statuses for a given ref. The ref can be a SHA, a branch name, or a tag name. - * - * Additionally, a combined `state` is returned. The `state` is one of: - * - * - **failure** if any of the contexts report as `error` or `failure` - * - **pending** if there are no statuses or a context is `pending` - * - **success** if the latest status for all contexts is `success` - * - * @example - * ```ts - * const response = await client.repos.commits.retrieveStatus( - * 'ref', - * { owner: 'owner', repo: 'repo' }, - * ); - * ``` - */ - retrieveStatus(ref, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/commits/${ref}/status`, { query, ...options }); + obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; + } else if (isArray(filter)) { + obj_keys = filter; + } else { + const keys = Object.keys(obj); + obj_keys = sort ? keys.sort(sort) : keys; + } + const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix); + const adjusted_prefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix; + if (allowEmptyArrays && isArray(obj) && obj.length === 0) { + return adjusted_prefix + "[]"; + } + for (let j = 0; j < obj_keys.length; ++j) { + const key = obj_keys[j]; + const value = ( + // @ts-ignore + typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key] + ); + if (skipNulls && value === null) { + continue; } + const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key; + const key_prefix = isArray(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]"); + sideChannel.set(object, step); + const valueSideChannel = /* @__PURE__ */ new WeakMap(); + valueSideChannel.set(sentinel, sideChannel); + push_to_array(values, inner_stringify( + value, + key_prefix, + generateArrayPrefix, + commaRoundTrip, + allowEmptyArrays, + strictNullHandling, + skipNulls, + encodeDotInKeys, + // @ts-ignore + generateArrayPrefix === "comma" && encodeValuesOnly && isArray(obj) ? null : encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + valueSideChannel + )); } - BaseCommits4._key = Object.freeze(["repos", "commits"]); - return BaseCommits4; -})(); - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/headers.mjs -var brand_privateNullableHeaders = /* @__PURE__ */ Symbol("brand.privateNullableHeaders"); -function* iterateHeaders(headers) { - if (!headers) - return; - if (brand_privateNullableHeaders in headers) { - const { values, nulls } = headers; - yield* values.entries(); - for (const name of nulls) { - yield [name, null]; + return values; +} +function normalize_stringify_options(opts = defaults) { + if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") { + throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); + } + if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") { + throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided"); + } + if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") { + throw new TypeError("Encoder has to be a function."); + } + const charset = opts.charset || defaults.charset; + if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { + throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); + } + let format = default_format; + if (typeof opts.format !== "undefined") { + if (!has(formatters, opts.format)) { + throw new TypeError("Unknown format option provided."); } - return; + format = opts.format; } - let shouldClear = false; - let iter; - if (headers instanceof Headers) { - iter = headers.entries(); - } else if (isReadonlyArray(headers)) { - iter = headers; + const formatter = formatters[format]; + let filter = defaults.filter; + if (typeof opts.filter === "function" || isArray(opts.filter)) { + filter = opts.filter; + } + let arrayFormat; + if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) { + arrayFormat = opts.arrayFormat; + } else if ("indices" in opts) { + arrayFormat = opts.indices ? "indices" : "repeat"; } else { - shouldClear = true; - iter = Object.entries(headers ?? {}); + arrayFormat = defaults.arrayFormat; } - for (let row of iter) { - const name = row[0]; - if (typeof name !== "string") - throw new TypeError("expected header name to be a string"); - const values = isReadonlyArray(row[1]) ? row[1] : [row[1]]; - let didClear = false; - for (const value of values) { - if (value === void 0) - continue; - if (shouldClear && !didClear) { - didClear = true; - yield [name, null]; - } - yield [name, value]; - } + if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") { + throw new TypeError("`commaRoundTrip` must be a boolean, or absent"); } + const allowDots = typeof opts.allowDots === "undefined" ? !!opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; + return { + addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix, + // @ts-ignore + allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, + arrayFormat, + charset, + charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel, + commaRoundTrip: !!opts.commaRoundTrip, + delimiter: typeof opts.delimiter === "undefined" ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === "boolean" ? opts.encode : defaults.encode, + encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults.encodeDotInKeys, + encoder: typeof opts.encoder === "function" ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter, + format, + formatter, + serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults.skipNulls, + // @ts-ignore + sort: typeof opts.sort === "function" ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling + }; } -var buildHeaders = (newHeaders) => { - const targetHeaders = new Headers(); - const nullHeaders = /* @__PURE__ */ new Set(); - for (const headers of newHeaders) { - const seenHeaders = /* @__PURE__ */ new Set(); - for (const [name, value] of iterateHeaders(headers)) { - const lowerName = name.toLowerCase(); - if (!seenHeaders.has(lowerName)) { - targetHeaders.delete(name); - seenHeaders.add(lowerName); - } - if (value === null) { - targetHeaders.delete(name); - nullHeaders.add(lowerName); - } else { - targetHeaders.append(name, value); - nullHeaders.delete(lowerName); - } +function stringify(object, opts = {}) { + let obj = object; + const options = normalize_stringify_options(opts); + let obj_keys; + let filter; + if (typeof options.filter === "function") { + filter = options.filter; + obj = filter("", obj); + } else if (isArray(options.filter)) { + filter = options.filter; + obj_keys = filter; + } + const keys = []; + if (typeof obj !== "object" || obj === null) { + return ""; + } + const generateArrayPrefix = array_prefix_generators[options.arrayFormat]; + const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip; + if (!obj_keys) { + obj_keys = Object.keys(obj); + } + if (options.sort) { + obj_keys.sort(options.sort); + } + const sideChannel = /* @__PURE__ */ new WeakMap(); + for (let i = 0; i < obj_keys.length; ++i) { + const key = obj_keys[i]; + if (options.skipNulls && obj[key] === null) { + continue; + } + push_to_array(keys, inner_stringify( + obj[key], + key, + // @ts-expect-error + generateArrayPrefix, + commaRoundTrip, + options.allowEmptyArrays, + options.strictNullHandling, + options.skipNulls, + options.encodeDotInKeys, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.format, + options.formatter, + options.encodeValuesOnly, + options.charset, + sideChannel + )); + } + const joined = keys.join(options.delimiter); + let prefix = options.addQueryPrefix === true ? "?" : ""; + if (options.charsetSentinel) { + if (options.charset === "iso-8859-1") { + prefix += "utf8=%26%2310003%3B&"; + } else { + prefix += "utf8=%E2%9C%93&"; } } - return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders }; -}; + return joined.length > 0 ? prefix + joined : ""; +} -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/resources/repos/issues/comments/comments.mjs -var BaseComments2 = /* @__PURE__ */ (() => { - class BaseComments8 extends APIResource { - /** - * You can use the REST API to create comments on issues and pull requests. Every - * pull request is an issue, but not every issue is a pull request. - * - * This endpoint triggers - * [notifications](https://docs.github.com/github/managing-subscriptions-and-notifications-on-github/about-notifications). - * Creating content too quickly using this endpoint may result in secondary rate - * limiting. For more information, see - * "[Rate limits for the API](https://docs.github.com/rest/using-the-rest-api/rate-limits-for-the-rest-api#about-secondary-rate-limits)" - * and - * "[Best practices for using the REST API](https://docs.github.com/rest/guides/best-practices-for-using-the-rest-api)." - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response - * will include `body`. This is the default if you do not pass any specific media - * type. - * - **`application/vnd.github.text+json`**: Returns a text only representation of - * the markdown body. Response will include `body_text`. - * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's - * markdown. Response will include `body_html`. - * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML - * representations. Response will include `body`, `body_text`, and `body_html`. - * - * @example - * ```ts - * const issueComment = - * await client.repos.issues.comments.create(0, { - * owner: 'owner', - * repo: 'repo', - * body: 'Me too', - * }); - * ``` - */ - create(issueNumber, params, options) { - const { owner = this._client.owner, repo = this._client.repo, ...body } = params; - return this._client.post(path`/repos/${owner}/${repo}/issues/${issueNumber}/comments`, { - body, - ...options - }); +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/query.mjs +function stringifyQuery(query) { + return stringify(query, { arrayFormat: "comma" }); +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/log.mjs +var levelNumbers = { + off: 0, + error: 200, + warn: 300, + info: 400, + debug: 500 +}; +var parseLogLevel = (maybeLevel, sourceName, client) => { + if (!maybeLevel) { + return void 0; + } + if (hasOwn(levelNumbers, maybeLevel)) { + return maybeLevel; + } + loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`); + return void 0; +}; +function noop() { +} +function makeLogFn(fnLevel, logger2, logLevel) { + if (!logger2 || levelNumbers[fnLevel] > levelNumbers[logLevel]) { + return noop; + } else { + return logger2[fnLevel].bind(logger2); + } +} +var noopLogger = { + error: noop, + warn: noop, + info: noop, + debug: noop +}; +var cachedLoggers = /* @__PURE__ */ new WeakMap(); +function loggerFor(client) { + const logger2 = client.logger; + const logLevel = client.logLevel ?? "off"; + if (!logger2) { + return noopLogger; + } + const cachedLogger = cachedLoggers.get(logger2); + if (cachedLogger && cachedLogger[0] === logLevel) { + return cachedLogger[1]; + } + const levelLogger = { + error: makeLogFn("error", logger2, logLevel), + warn: makeLogFn("warn", logger2, logLevel), + info: makeLogFn("info", logger2, logLevel), + debug: makeLogFn("debug", logger2, logLevel) + }; + cachedLoggers.set(logger2, [logLevel, levelLogger]); + return levelLogger; +} +var formatRequestDetails = (details) => { + if (details.options) { + details.options = { ...details.options }; + delete details.options["headers"]; + } + if (details.headers) { + details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ + name, + name.toLowerCase() === "authorization" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value + ])); + } + if ("retryOfRequestLogID" in details) { + if (details.retryOfRequestLogID) { + details.retryOf = details.retryOfRequestLogID; } - /** - * You can use the REST API to get comments on issues and pull requests. Every pull - * request is an issue, but not every issue is a pull request. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response - * will include `body`. This is the default if you do not pass any specific media - * type. - * - **`application/vnd.github.text+json`**: Returns a text only representation of - * the markdown body. Response will include `body_text`. - * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's - * markdown. Response will include `body_html`. - * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML - * representations. Response will include `body`, `body_text`, and `body_html`. - * - * @example - * ```ts - * const issueComment = - * await client.repos.issues.comments.retrieve(0, { - * owner: 'owner', - * repo: 'repo', - * }); - * ``` - */ - retrieve(commentID, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/issues/comments/${commentID}`, options); + delete details.retryOfRequestLogID; + } + return details; +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/parse.mjs +async function defaultParseResponse(client, props) { + const { response, requestLogID, retryOfRequestLogID, startTime } = props; + const body = await (async () => { + if (response.status === 204) { + return null; } - /** - * You can use the REST API to update comments on issues and pull requests. Every - * pull request is an issue, but not every issue is a pull request. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response - * will include `body`. This is the default if you do not pass any specific media - * type. - * - **`application/vnd.github.text+json`**: Returns a text only representation of - * the markdown body. Response will include `body_text`. - * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's - * markdown. Response will include `body_html`. - * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML - * representations. Response will include `body`, `body_text`, and `body_html`. - * - * @example - * ```ts - * const issueComment = - * await client.repos.issues.comments.update(0, { - * owner: 'owner', - * repo: 'repo', - * body: 'Me too', - * }); - * ``` - */ - update(commentID, params, options) { - const { owner = this._client.owner, repo = this._client.repo, ...body } = params; - return this._client.patch(path`/repos/${owner}/${repo}/issues/comments/${commentID}`, { - body, - ...options - }); + if (props.options.__binaryResponse) { + return response; } - async upsertBasedOnBodyMatch(issueNumber, { bodyIncludes, createParams, updateParams, options }) { - const comments = await this.list(issueNumber); - const match = comments.data.find((comment) => comment.body?.includes(bodyIncludes)); - if (match) { - return this.update(match.id, updateParams, options); - } else { - return this.create(issueNumber, createParams, options); + const contentType = response.headers.get("content-type"); + const mediaType = contentType?.split(";")[0]?.trim(); + const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json"); + if (isJSON) { + const contentLength = response.headers.get("content-length"); + if (contentLength === "0") { + return void 0; } + const json = await response.json(); + return json; } - /** - * You can use the REST API to list comments on issues and pull requests. Every - * pull request is an issue, but not every issue is a pull request. - * - * Issue comments are ordered by ascending ID. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response - * will include `body`. This is the default if you do not pass any specific media - * type. - * - **`application/vnd.github.text+json`**: Returns a text only representation of - * the markdown body. Response will include `body_text`. - * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's - * markdown. Response will include `body_html`. - * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML - * representations. Response will include `body`, `body_text`, and `body_html`. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const issueComment of client.repos.issues.comments.list( - * 0, - * { owner: 'owner', repo: 'repo' }, - * )) { - * // ... - * } - * ``` - */ - list(issueNumber, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.getAPIList(path`/repos/${owner}/${repo}/issues/${issueNumber}/comments`, NumberedPage, { query, ...options }); - } - /** - * You can use the REST API to delete comments on issues and pull requests. Every - * pull request is an issue, but not every issue is a pull request. - * - * @example - * ```ts - * await client.repos.issues.comments.delete(0, { - * owner: 'owner', - * repo: 'repo', - * }); - * ``` - */ - delete(commentID, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; - return this._client.delete(path`/repos/${owner}/${repo}/issues/comments/${commentID}`, { - ...options, - headers: buildHeaders([{ Accept: "*/*" }, options?.headers]) - }); - } - } - BaseComments8._key = Object.freeze([ - "repos", - "issues", - "comments" - ]); - return BaseComments8; -})(); - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/resources/repos/pulls/pulls.mjs -var BasePulls = /* @__PURE__ */ (() => { - class BasePulls2 extends APIResource { - /** - * Draft pull requests are available in public repositories with GitHub Free and - * GitHub Free for organizations, GitHub Pro, and legacy per-repository billing - * plans, and in public and private repositories with GitHub Team and GitHub - * Enterprise Cloud. For more information, see - * [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) - * in the GitHub Help documentation. - * - * To open or update a pull request in a public repository, you must have write - * access to the head or the source branch. For organization-owned repositories, - * you must be a member of the organization that owns the repository to open or - * update a pull request. - * - * This endpoint triggers - * [notifications](https://docs.github.com/github/managing-subscriptions-and-notifications-on-github/about-notifications). - * Creating content too quickly using this endpoint may result in secondary rate - * limiting. For more information, see - * "[Rate limits for the API](https://docs.github.com/rest/using-the-rest-api/rate-limits-for-the-rest-api#about-secondary-rate-limits)" - * and - * "[Best practices for using the REST API](https://docs.github.com/rest/guides/best-practices-for-using-the-rest-api)." - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response - * will include `body`. This is the default if you do not pass any specific media - * type. - * - **`application/vnd.github.text+json`**: Returns a text only representation of - * the markdown body. Response will include `body_text`. - * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's - * markdown. Response will include `body_html`. - * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML - * representations. Response will include `body`, `body_text`, and `body_html`. - * - * @example - * ```ts - * const pullRequest = await client.repos.pulls.create({ - * owner: 'owner', - * repo: 'repo', - * base: 'master', - * head: 'octocat:new-feature', - * body: 'Please pull these awesome changes in!', - * title: 'Amazing new feature', - * }); - * ``` - */ - create(params, options) { - const { owner = this._client.owner, repo = this._client.repo, ...body } = params; - return this._client.post(path`/repos/${owner}/${repo}/pulls`, { body, ...options }); - } - /** - * Draft pull requests are available in public repositories with GitHub Free and - * GitHub Free for organizations, GitHub Pro, and legacy per-repository billing - * plans, and in public and private repositories with GitHub Team and GitHub - * Enterprise Cloud. For more information, see - * [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) - * in the GitHub Help documentation. - * - * Lists details of a pull request by providing its number. - * - * When you get, - * [create](https://docs.github.com/rest/pulls/pulls/#create-a-pull-request), or - * [edit](https://docs.github.com/rest/pulls/pulls#update-a-pull-request) a pull - * request, GitHub creates a merge commit to test whether the pull request can be - * automatically merged into the base branch. This test commit is not added to the - * base branch or the head branch. You can review the status of the test commit - * using the `mergeable` key. For more information, see - * "[Checking mergeability of pull requests](https://docs.github.com/rest/guides/getting-started-with-the-git-database-api#checking-mergeability-of-pull-requests)". - * - * The value of the `mergeable` attribute can be `true`, `false`, or `null`. If the - * value is `null`, then GitHub has started a background job to compute the - * mergeability. After giving the job time to complete, resubmit the request. When - * the job finishes, you will see a non-`null` value for the `mergeable` attribute - * in the response. If `mergeable` is `true`, then `merge_commit_sha` will be the - * SHA of the _test_ merge commit. - * - * The value of the `merge_commit_sha` attribute changes depending on the state of - * the pull request. Before merging a pull request, the `merge_commit_sha` - * attribute holds the SHA of the _test_ merge commit. After merging a pull - * request, the `merge_commit_sha` attribute changes depending on how you merged - * the pull request: - * - * - If merged as a - * [merge commit](https://docs.github.com/articles/about-merge-methods-on-github/), - * `merge_commit_sha` represents the SHA of the merge commit. - * - If merged via a - * [squash](https://docs.github.com/articles/about-merge-methods-on-github/#squashing-your-merge-commits), - * `merge_commit_sha` represents the SHA of the squashed commit on the base - * branch. - * - If - * [rebased](https://docs.github.com/articles/about-merge-methods-on-github/#rebasing-and-merging-your-commits), - * `merge_commit_sha` represents the commit that the base branch was updated to. - * - * Pass the appropriate - * [media type](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types) - * to fetch diff and patch formats. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response - * will include `body`. This is the default if you do not pass any specific media - * type. - * - **`application/vnd.github.text+json`**: Returns a text only representation of - * the markdown body. Response will include `body_text`. - * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's - * markdown. Response will include `body_html`. - * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML - * representations. Response will include `body`, `body_text`, and `body_html`. - * - **`application/vnd.github.diff`**: For more information, see - * "[git-diff](https://git-scm.com/docs/git-diff)" in the Git documentation. If a - * diff is corrupt, contact us through the - * [GitHub Support portal](https://support.github.com/). Include the repository - * name and pull request ID in your message. - * - * @example - * ```ts - * const pullRequest = await client.repos.pulls.retrieve(0, { - * owner: 'owner', - * repo: 'repo', - * }); - * ``` - */ - retrieve(pullNumber, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/pulls/${pullNumber}`, options); - } - /** - * Draft pull requests are available in public repositories with GitHub Free and - * GitHub Free for organizations, GitHub Pro, and legacy per-repository billing - * plans, and in public and private repositories with GitHub Team and GitHub - * Enterprise Cloud. For more information, see - * [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) - * in the GitHub Help documentation. - * - * To open or update a pull request in a public repository, you must have write - * access to the head or the source branch. For organization-owned repositories, - * you must be a member of the organization that owns the repository to open or - * update a pull request. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response - * will include `body`. This is the default if you do not pass any specific media - * type. - * - **`application/vnd.github.text+json`**: Returns a text only representation of - * the markdown body. Response will include `body_text`. - * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's - * markdown. Response will include `body_html`. - * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML - * representations. Response will include `body`, `body_text`, and `body_html`. - * - * @example - * ```ts - * const pullRequest = await client.repos.pulls.update(0, { - * owner: 'owner', - * repo: 'repo', - * base: 'master', - * body: 'updated body', - * state: 'open', - * title: 'new title', - * }); - * ``` - */ - update(pullNumber, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...body } = params ?? {}; - return this._client.patch(path`/repos/${owner}/${repo}/pulls/${pullNumber}`, { body, ...options }); - } - /** - * Lists pull requests in a specified repository. - * - * Draft pull requests are available in public repositories with GitHub Free and - * GitHub Free for organizations, GitHub Pro, and legacy per-repository billing - * plans, and in public and private repositories with GitHub Team and GitHub - * Enterprise Cloud. For more information, see - * [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) - * in the GitHub Help documentation. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response - * will include `body`. This is the default if you do not pass any specific media - * type. - * - **`application/vnd.github.text+json`**: Returns a text only representation of - * the markdown body. Response will include `body_text`. - * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's - * markdown. Response will include `body_html`. - * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML - * representations. Response will include `body`, `body_text`, and `body_html`. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const pullRequestSimple of client.repos.pulls.list( - * { owner: 'owner', repo: 'repo' }, - * )) { - * // ... - * } - * ``` - */ - list(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.getAPIList(path`/repos/${owner}/${repo}/pulls`, NumberedPage, { - query, - ...options - }); - } - /** - * Creates a codespace owned by the authenticated user for the specified pull - * request. - * - * OAuth app tokens and personal access tokens (classic) need the `codespace` scope - * to use this endpoint. - * - * @example - * ```ts - * const codespace = await client.repos.pulls.createCodespace( - * 0, - * { owner: 'owner', repo: 'repo' }, - * ); - * ``` - */ - createCodespace(pullNumber, params, options) { - const { owner = this._client.owner, repo = this._client.repo, ...body } = params; - return this._client.post(path`/repos/${owner}/${repo}/pulls/${pullNumber}/codespaces`, { - body, - ...options - }); - } - /** - * Creates a review comment on the diff of a specified pull request. To add a - * regular comment to a pull request timeline, see - * "[Create an issue comment](https://docs.github.com/rest/issues/comments#create-an-issue-comment)." - * - * If your comment applies to more than one line in the pull request diff, you - * should use the parameters `line`, `side`, and optionally `start_line` and - * `start_side` in your request. - * - * The `position` parameter is closing down. If you use `position`, the `line`, - * `side`, `start_line`, and `start_side` parameters are not required. - * - * This endpoint triggers - * [notifications](https://docs.github.com/github/managing-subscriptions-and-notifications-on-github/about-notifications). - * Creating content too quickly using this endpoint may result in secondary rate - * limiting. For more information, see - * "[Rate limits for the API](https://docs.github.com/rest/using-the-rest-api/rate-limits-for-the-rest-api#about-secondary-rate-limits)" - * and - * "[Best practices for using the REST API](https://docs.github.com/rest/guides/best-practices-for-using-the-rest-api)." - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github-commitcomment.raw+json`**: Returns the raw markdown - * body. Response will include `body`. This is the default if you do not pass any - * specific media type. - * - **`application/vnd.github-commitcomment.text+json`**: Returns a text only - * representation of the markdown body. Response will include `body_text`. - * - **`application/vnd.github-commitcomment.html+json`**: Returns HTML rendered - * from the body's markdown. Response will include `body_html`. - * - **`application/vnd.github-commitcomment.full+json`**: Returns raw, text, and - * HTML representations. Response will include `body`, `body_text`, and - * `body_html`. - * - * @example - * ```ts - * const response = await client.repos.pulls.createComment(0, { - * owner: 'owner', - * repo: 'repo', - * body: 'Great stuff!', - * commit_id: '6dcb09b5b57875f334f61aebed695e2e4193db5e', - * path: 'file1.txt', - * line: 2, - * side: 'RIGHT', - * start_line: 1, - * start_side: 'RIGHT', - * }); - * ``` - */ - createComment(pullNumber, params, options) { - const { owner = this._client.owner, repo = this._client.repo, ...body } = params; - return this._client.post(path`/repos/${owner}/${repo}/pulls/${pullNumber}/comments`, { - body, - ...options - }); - } - /** - * Lists all review comments for a specified pull request. By default, review - * comments are in ascending order by ID. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github-commitcomment.raw+json`**: Returns the raw markdown - * body. Response will include `body`. This is the default if you do not pass any - * specific media type. - * - **`application/vnd.github-commitcomment.text+json`**: Returns a text only - * representation of the markdown body. Response will include `body_text`. - * - **`application/vnd.github-commitcomment.html+json`**: Returns HTML rendered - * from the body's markdown. Response will include `body_html`. - * - **`application/vnd.github-commitcomment.full+json`**: Returns raw, text, and - * HTML representations. Response will include `body`, `body_text`, and - * `body_html`. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const pullListCommentsResponse of client.repos.pulls.listComments( - * 0, - * { owner: 'owner', repo: 'repo' }, - * )) { - * // ... - * } - * ``` - */ - listComments(pullNumber, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.getAPIList(path`/repos/${owner}/${repo}/pulls/${pullNumber}/comments`, NumberedPage, { query, ...options }); - } - /** - * Lists a maximum of 250 commits for a pull request. To receive a complete commit - * list for pull requests with more than 250 commits, use the - * [List commits](https://docs.github.com/rest/commits/commits#list-commits) - * endpoint. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response - * will include `body`. This is the default if you do not pass any specific media - * type. - * - **`application/vnd.github.text+json`**: Returns a text only representation of - * the markdown body. Response will include `body_text`. - * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's - * markdown. Response will include `body_html`. - * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML - * representations. Response will include `body`, `body_text`, and `body_html`. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const commit of client.repos.pulls.listCommits( - * 0, - * { owner: 'owner', repo: 'repo' }, - * )) { - * // ... - * } - * ``` - */ - listCommits(pullNumber, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.getAPIList(path`/repos/${owner}/${repo}/pulls/${pullNumber}/commits`, NumberedPage, { query, ...options }); - } - /** - * Lists the files in a specified pull request. - * - * > [!NOTE] Responses include a maximum of 3000 files. The paginated response - * > returns 30 files per page by default. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response - * will include `body`. This is the default if you do not pass any specific media - * type. - * - **`application/vnd.github.text+json`**: Returns a text only representation of - * the markdown body. Response will include `body_text`. - * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's - * markdown. Response will include `body_html`. - * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML - * representations. Response will include `body`, `body_text`, and `body_html`. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const pullListFilesResponse of client.repos.pulls.listFiles( - * 0, - * { owner: 'owner', repo: 'repo' }, - * )) { - * // ... - * } - * ``` - */ - listFiles(pullNumber, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.getAPIList(path`/repos/${owner}/${repo}/pulls/${pullNumber}/files`, NumberedPage, { query, ...options }); - } - /** - * Updates the pull request branch with the latest upstream changes by merging HEAD - * from the base branch into the pull request branch. Note: If making a request on - * behalf of a GitHub App you must also have permissions to write the contents of - * the head repository. - * - * @example - * ```ts - * const response = await client.repos.pulls.updateBranch(0, { - * owner: 'owner', - * repo: 'repo', - * expected_head_sha: - * '6dcb09b5b57875f334f61aebed695e2e4193db5e', - * }); - * ``` - */ - updateBranch(pullNumber, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...body } = params ?? {}; - return this._client.put(path`/repos/${owner}/${repo}/pulls/${pullNumber}/update-branch`, { - body, - ...options - }); - } - } - BasePulls2._key = Object.freeze(["repos", "pulls"]); - return BasePulls2; -})(); - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/utils/uuid.mjs -var uuid4 = function() { - const { crypto: crypto2 } = globalThis; - if (crypto2?.randomUUID) { - uuid4 = crypto2.randomUUID.bind(crypto2); - return crypto2.randomUUID(); - } - const u8 = new Uint8Array(1); - const randomByte = crypto2 ? () => crypto2.getRandomValues(u8)[0] : () => Math.random() * 255 & 255; - return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16)); -}; - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/utils/sleep.mjs -var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/version.mjs -var VERSION = "0.25.1"; - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/detect-platform.mjs -function getDetectedPlatform() { - if (typeof Deno !== "undefined" && Deno.build != null) { - return "deno"; - } - if (typeof EdgeRuntime !== "undefined") { - return "edge"; - } - if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") { - return "node"; - } - return "unknown"; -} -var getPlatformProperties = () => { - const detectedPlatform = getDetectedPlatform(); - if (detectedPlatform === "deno") { - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION, - "X-Stainless-OS": normalizePlatform(Deno.build.os), - "X-Stainless-Arch": normalizeArch(Deno.build.arch), - "X-Stainless-Runtime": "deno", - "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown" - }; - } - if (typeof EdgeRuntime !== "undefined") { - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION, - "X-Stainless-OS": "Unknown", - "X-Stainless-Arch": `other:${EdgeRuntime}`, - "X-Stainless-Runtime": "edge", - "X-Stainless-Runtime-Version": globalThis.process.version - }; - } - if (detectedPlatform === "node") { - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION, - "X-Stainless-OS": normalizePlatform(globalThis.process.platform ?? "unknown"), - "X-Stainless-Arch": normalizeArch(globalThis.process.arch ?? "unknown"), - "X-Stainless-Runtime": "node", - "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown" - }; - } - const browserInfo = getBrowserInfo(); - if (browserInfo) { - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION, - "X-Stainless-OS": "Unknown", - "X-Stainless-Arch": "unknown", - "X-Stainless-Runtime": `browser:${browserInfo.browser}`, - "X-Stainless-Runtime-Version": browserInfo.version - }; - } - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION, - "X-Stainless-OS": "Unknown", - "X-Stainless-Arch": "unknown", - "X-Stainless-Runtime": "unknown", - "X-Stainless-Runtime-Version": "unknown" - }; -}; -function getBrowserInfo() { - if (typeof navigator === "undefined" || !navigator) { - return null; - } - const browserPatterns = [ - { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ } - ]; - for (const { key, pattern } of browserPatterns) { - const match = pattern.exec(navigator.userAgent); - if (match) { - const major = match[1] || 0; - const minor = match[2] || 0; - const patch = match[3] || 0; - return { browser: key, version: `${major}.${minor}.${patch}` }; - } - } - return null; -} -var normalizeArch = (arch) => { - if (arch === "x32") - return "x32"; - if (arch === "x86_64" || arch === "x64") - return "x64"; - if (arch === "arm") - return "arm"; - if (arch === "aarch64" || arch === "arm64") - return "arm64"; - if (arch) - return `other:${arch}`; - return "unknown"; -}; -var normalizePlatform = (platform) => { - platform = platform.toLowerCase(); - if (platform.includes("ios")) - return "iOS"; - if (platform === "android") - return "Android"; - if (platform === "darwin") - return "MacOS"; - if (platform === "win32") - return "Windows"; - if (platform === "freebsd") - return "FreeBSD"; - if (platform === "openbsd") - return "OpenBSD"; - if (platform === "linux") - return "Linux"; - if (platform) - return `Other:${platform}`; - return "Unknown"; -}; -var _platformHeaders; -var getPlatformHeaders = () => { - return _platformHeaders ?? (_platformHeaders = getPlatformProperties()); -}; - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/shims.mjs -function getDefaultFetch() { - if (typeof fetch !== "undefined") { - return fetch; - } - throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new GitHub({ fetch })` or polyfill the global, `globalThis.fetch = fetch`"); -} -function makeReadableStream(...args) { - const ReadableStream = globalThis.ReadableStream; - if (typeof ReadableStream === "undefined") { - throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`"); - } - return new ReadableStream(...args); -} -function ReadableStreamFrom(iterable) { - let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); - return makeReadableStream({ - start() { - }, - async pull(controller) { - const { done, value } = await iter.next(); - if (done) { - controller.close(); - } else { - controller.enqueue(value); - } - }, - async cancel() { - await iter.return?.(); - } - }); -} -async function CancelReadableStream(stream) { - if (stream === null || typeof stream !== "object") - return; - if (stream[Symbol.asyncIterator]) { - await stream[Symbol.asyncIterator]().return?.(); - return; - } - const reader = stream.getReader(); - const cancelPromise = reader.cancel(); - reader.releaseLock(); - await cancelPromise; -} - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/request-options.mjs -var FallbackEncoder = ({ headers, body }) => { - return { - bodyHeaders: { - "content-type": "application/json" - }, - body: JSON.stringify(body) - }; -}; - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/qs/formats.mjs -var default_format = "RFC3986"; -var default_formatter = (v) => String(v); -var formatters = { - RFC1738: (v) => String(v).replace(/%20/g, "+"), - RFC3986: default_formatter -}; -var RFC1738 = "RFC1738"; - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/qs/utils.mjs -var has = (obj, key) => (has = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has(obj, key)); -var hex_table = /* @__PURE__ */ (() => { - const array = []; - for (let i = 0; i < 256; ++i) { - array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase()); - } - return array; -})(); -var limit = 1024; -var encode = (str, _defaultEncoder, charset, _kind, format) => { - if (str.length === 0) { - return str; - } - let string = str; - if (typeof str === "symbol") { - string = Symbol.prototype.toString.call(str); - } else if (typeof str !== "string") { - string = String(str); - } - if (charset === "iso-8859-1") { - return escape(string).replace(/%u[0-9a-f]{4}/gi, function($0) { - return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; - }); - } - let out = ""; - for (let j = 0; j < string.length; j += limit) { - const segment = string.length >= limit ? string.slice(j, j + limit) : string; - const arr = []; - for (let i = 0; i < segment.length; ++i) { - let c = segment.charCodeAt(i); - if (c === 45 || // - - c === 46 || // . - c === 95 || // _ - c === 126 || // ~ - c >= 48 && c <= 57 || // 0-9 - c >= 65 && c <= 90 || // a-z - c >= 97 && c <= 122 || // A-Z - format === RFC1738 && (c === 40 || c === 41)) { - arr[arr.length] = segment.charAt(i); - continue; - } - if (c < 128) { - arr[arr.length] = hex_table[c]; - continue; - } - if (c < 2048) { - arr[arr.length] = hex_table[192 | c >> 6] + hex_table[128 | c & 63]; - continue; - } - if (c < 55296 || c >= 57344) { - arr[arr.length] = hex_table[224 | c >> 12] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63]; - continue; - } - i += 1; - c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023); - arr[arr.length] = hex_table[240 | c >> 18] + hex_table[128 | c >> 12 & 63] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63]; - } - out += arr.join(""); - } - return out; -}; -function is_buffer(obj) { - if (!obj || typeof obj !== "object") { - return false; - } - return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); -} -function maybe_map(val, fn) { - if (isArray(val)) { - const mapped = []; - for (let i = 0; i < val.length; i += 1) { - mapped.push(fn(val[i])); - } - return mapped; - } - return fn(val); -} - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/qs/stringify.mjs -var array_prefix_generators = { - brackets(prefix) { - return String(prefix) + "[]"; - }, - comma: "comma", - indices(prefix, key) { - return String(prefix) + "[" + key + "]"; - }, - repeat(prefix) { - return String(prefix); - } -}; -var push_to_array = function(arr, value_or_array) { - Array.prototype.push.apply(arr, isArray(value_or_array) ? value_or_array : [value_or_array]); -}; -var toISOString; -var defaults = { - addQueryPrefix: false, - allowDots: false, - allowEmptyArrays: false, - arrayFormat: "indices", - charset: "utf-8", - charsetSentinel: false, - delimiter: "&", - encode: true, - encodeDotInKeys: false, - encoder: encode, - encodeValuesOnly: false, - format: default_format, - formatter: default_formatter, - /** @deprecated */ - indices: false, - serializeDate(date) { - return (toISOString ?? (toISOString = Function.prototype.call.bind(Date.prototype.toISOString)))(date); - }, - skipNulls: false, - strictNullHandling: false -}; -function is_non_nullish_primitive(v) { - return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint"; -} -var sentinel = {}; -function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { - let obj = object; - let tmp_sc = sideChannel; - let step = 0; - let find_flag = false; - while ((tmp_sc = tmp_sc.get(sentinel)) !== void 0 && !find_flag) { - const pos = tmp_sc.get(object); - step += 1; - if (typeof pos !== "undefined") { - if (pos === step) { - throw new RangeError("Cyclic object value"); - } else { - find_flag = true; - } - } - if (typeof tmp_sc.get(sentinel) === "undefined") { - step = 0; - } - } - if (typeof filter === "function") { - obj = filter(prefix, obj); - } else if (obj instanceof Date) { - obj = serializeDate?.(obj); - } else if (generateArrayPrefix === "comma" && isArray(obj)) { - obj = maybe_map(obj, function(value) { - if (value instanceof Date) { - return serializeDate?.(value); - } - return value; - }); - } - if (obj === null) { - if (strictNullHandling) { - return encoder && !encodeValuesOnly ? ( - // @ts-expect-error - encoder(prefix, defaults.encoder, charset, "key", format) - ) : prefix; - } - obj = ""; - } - if (is_non_nullish_primitive(obj) || is_buffer(obj)) { - if (encoder) { - const key_value = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, "key", format); - return [ - formatter?.(key_value) + "=" + // @ts-expect-error - formatter?.(encoder(obj, defaults.encoder, charset, "value", format)) - ]; - } - return [formatter?.(prefix) + "=" + formatter?.(String(obj))]; - } - const values = []; - if (typeof obj === "undefined") { - return values; - } - let obj_keys; - if (generateArrayPrefix === "comma" && isArray(obj)) { - if (encodeValuesOnly && encoder) { - obj = maybe_map(obj, encoder); - } - obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; - } else if (isArray(filter)) { - obj_keys = filter; - } else { - const keys = Object.keys(obj); - obj_keys = sort ? keys.sort(sort) : keys; - } - const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix); - const adjusted_prefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix; - if (allowEmptyArrays && isArray(obj) && obj.length === 0) { - return adjusted_prefix + "[]"; - } - for (let j = 0; j < obj_keys.length; ++j) { - const key = obj_keys[j]; - const value = ( - // @ts-ignore - typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key] - ); - if (skipNulls && value === null) { - continue; - } - const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key; - const key_prefix = isArray(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]"); - sideChannel.set(object, step); - const valueSideChannel = /* @__PURE__ */ new WeakMap(); - valueSideChannel.set(sentinel, sideChannel); - push_to_array(values, inner_stringify( - value, - key_prefix, - generateArrayPrefix, - commaRoundTrip, - allowEmptyArrays, - strictNullHandling, - skipNulls, - encodeDotInKeys, - // @ts-ignore - generateArrayPrefix === "comma" && encodeValuesOnly && isArray(obj) ? null : encoder, - filter, - sort, - allowDots, - serializeDate, - format, - formatter, - encodeValuesOnly, - charset, - valueSideChannel - )); - } - return values; -} -function normalize_stringify_options(opts = defaults) { - if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") { - throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); - } - if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") { - throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided"); - } - if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") { - throw new TypeError("Encoder has to be a function."); - } - const charset = opts.charset || defaults.charset; - if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { - throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); - } - let format = default_format; - if (typeof opts.format !== "undefined") { - if (!has(formatters, opts.format)) { - throw new TypeError("Unknown format option provided."); - } - format = opts.format; - } - const formatter = formatters[format]; - let filter = defaults.filter; - if (typeof opts.filter === "function" || isArray(opts.filter)) { - filter = opts.filter; - } - let arrayFormat; - if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) { - arrayFormat = opts.arrayFormat; - } else if ("indices" in opts) { - arrayFormat = opts.indices ? "indices" : "repeat"; - } else { - arrayFormat = defaults.arrayFormat; - } - if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") { - throw new TypeError("`commaRoundTrip` must be a boolean, or absent"); - } - const allowDots = typeof opts.allowDots === "undefined" ? !!opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; - return { - addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix, - // @ts-ignore - allowDots, - allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, - arrayFormat, - charset, - charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel, - commaRoundTrip: !!opts.commaRoundTrip, - delimiter: typeof opts.delimiter === "undefined" ? defaults.delimiter : opts.delimiter, - encode: typeof opts.encode === "boolean" ? opts.encode : defaults.encode, - encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults.encodeDotInKeys, - encoder: typeof opts.encoder === "function" ? opts.encoder : defaults.encoder, - encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults.encodeValuesOnly, - filter, - format, - formatter, - serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults.serializeDate, - skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults.skipNulls, - // @ts-ignore - sort: typeof opts.sort === "function" ? opts.sort : null, - strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling - }; -} -function stringify(object, opts = {}) { - let obj = object; - const options = normalize_stringify_options(opts); - let obj_keys; - let filter; - if (typeof options.filter === "function") { - filter = options.filter; - obj = filter("", obj); - } else if (isArray(options.filter)) { - filter = options.filter; - obj_keys = filter; - } - const keys = []; - if (typeof obj !== "object" || obj === null) { - return ""; - } - const generateArrayPrefix = array_prefix_generators[options.arrayFormat]; - const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip; - if (!obj_keys) { - obj_keys = Object.keys(obj); - } - if (options.sort) { - obj_keys.sort(options.sort); - } - const sideChannel = /* @__PURE__ */ new WeakMap(); - for (let i = 0; i < obj_keys.length; ++i) { - const key = obj_keys[i]; - if (options.skipNulls && obj[key] === null) { - continue; - } - push_to_array(keys, inner_stringify( - obj[key], - key, - // @ts-expect-error - generateArrayPrefix, - commaRoundTrip, - options.allowEmptyArrays, - options.strictNullHandling, - options.skipNulls, - options.encodeDotInKeys, - options.encode ? options.encoder : null, - options.filter, - options.sort, - options.allowDots, - options.serializeDate, - options.format, - options.formatter, - options.encodeValuesOnly, - options.charset, - sideChannel - )); - } - const joined = keys.join(options.delimiter); - let prefix = options.addQueryPrefix === true ? "?" : ""; - if (options.charsetSentinel) { - if (options.charset === "iso-8859-1") { - prefix += "utf8=%26%2310003%3B&"; - } else { - prefix += "utf8=%E2%9C%93&"; - } - } - return joined.length > 0 ? prefix + joined : ""; -} - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/resources/apps/installations/installations.mjs -var BaseInstallations = /* @__PURE__ */ (() => { - class BaseInstallations4 extends APIResource { - /** - * Enables an authenticated GitHub App to find an installation's information using - * the installation id. - * - * You must use a - * [JWT](https://docs.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) - * to access this endpoint. - * - * @example - * ```ts - * const installation = - * await client.apps.installations.retrieve(0); - * ``` - */ - retrieve(installationID, options) { - return this._client.get(path`/app/installations/${installationID}`, options); - } - /** - * The permissions the installation has are included under the `permissions` key. - * - * You must use a - * [JWT](https://docs.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) - * to access this endpoint. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const installation of client.apps.installations.list()) { - * // ... - * } - * ``` - */ - list(query = {}, options) { - return this._client.getAPIList("/app/installations", NumberedPage, { - query, - ...options - }); - } - /** - * Uninstalls a GitHub App on a user, organization, or enterprise account. If you - * prefer to temporarily suspend an app's access to your account's resources, then - * we recommend the - * "[Suspend an app installation](https://docs.github.com/rest/apps/apps#suspend-an-app-installation)" - * endpoint. - * - * You must use a - * [JWT](https://docs.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) - * to access this endpoint. - * - * @example - * ```ts - * await client.apps.installations.delete(0); - * ``` - */ - delete(installationID, options) { - return this._client.delete(path`/app/installations/${installationID}`, { - ...options, - headers: buildHeaders([{ Accept: "*/*" }, options?.headers]) - }); - } - /** - * Creates an installation access token that enables a GitHub App to make - * authenticated API requests for the app's installation on an organization or - * individual account. Installation tokens expire one hour from the time you create - * them. Using an expired token produces a status code of `401 - Unauthorized`, and - * requires creating a new installation token. By default the installation token - * has access to all repositories that the installation can access. - * - * Optionally, you can use the `repositories` or `repository_ids` body parameters - * to specify individual repositories that the installation access token can - * access. If you don't use `repositories` or `repository_ids` to grant access to - * specific repositories, the installation access token will have access to all - * repositories that the installation was granted access to. The installation - * access token cannot be granted access to repositories that the installation was - * not granted access to. Up to 500 repositories can be listed in this manner. - * - * Optionally, use the `permissions` body parameter to specify the permissions that - * the installation access token should have. If `permissions` is not specified, - * the installation access token will have all of the permissions that were granted - * to the app. The installation access token cannot be granted permissions that the - * app was not granted. - * - * You must use a - * [JWT](https://docs.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) - * to access this endpoint. - * - * @example - * ```ts - * const response = - * await client.apps.installations.createAccessToken(0, { - * permissions: { issues: 'write', contents: 'read' }, - * repositories: ['Hello-World'], - * }); - * ``` - */ - createAccessToken(installationID, body = {}, options) { - return this._client.post(path`/app/installations/${installationID}/access_tokens`, { body, ...options }); - } - } - BaseInstallations4._key = Object.freeze([ - "apps", - "installations" - ]); - return BaseInstallations4; -})(); - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/resources/orgs/orgs.mjs -var BaseOrgs = /* @__PURE__ */ (() => { - class BaseOrgs3 extends APIResource { - /** - * Gets information about an organization. - * - * When the value of `two_factor_requirement_enabled` is `true`, the organization - * requires all members, billing managers, outside collaborators, guest - * collaborators, repository collaborators, or everyone with access to any - * repository within the organization to enable - * [two-factor authentication](https://docs.github.com/articles/securing-your-account-with-two-factor-authentication-2fa/). - * - * To see the full details about an organization, the authenticated user must be an - * organization owner. - * - * OAuth app tokens and personal access tokens (classic) need the `admin:org` scope - * to see the full details about an organization. - * - * To see information about an organization's GitHub plan, GitHub Apps need the - * `Organization plan` permission. - * - * @example - * ```ts - * const org = await client.orgs.retrieve('org'); - * ``` - */ - retrieve(org, options) { - return this._client.get(path`/orgs/${org}`, options); - } - /** - * > [!WARNING] > **Closing down notice:** GitHub will replace and discontinue - * > `members_allowed_repository_creation_type` in favor of more granular - * > permissions. The new input parameters are - * > `members_can_create_public_repositories`, - * > `members_can_create_private_repositories` for all organizations and - * > `members_can_create_internal_repositories` for organizations associated with - * > an enterprise account using GitHub Enterprise Cloud or GitHub Enterprise - * > Server 2.20+. For more information, see the - * > [blog post](https://developer.github.com/changes/2019-12-03-internal-visibility-changes). - * - * > [!WARNING] > **Closing down notice:** Code security product enablement for new - * > repositories through the organization API is closing down. Please use - * > [code security configurations](https://docs.github.com/rest/code-security/configurations#set-a-code-security-configuration-as-a-default-for-an-organization) - * > to set defaults instead. For more information on setting a default security - * > configuration, see the - * > [changelog](https://github.blog/changelog/2024-07-09-sunsetting-security-settings-defaults-parameters-in-the-organizations-rest-api/). - * - * Updates the organization's profile and member privileges. - * - * The authenticated user must be an organization owner to use this endpoint. - * - * OAuth app tokens and personal access tokens (classic) need the `admin:org` or - * `repo` scope to use this endpoint. - * - * @example - * ```ts - * const org = await client.orgs.update('org', { - * billing_email: 'mona@github.com', - * company: 'GitHub', - * default_repository_permission: 'read', - * description: 'GitHub, the company.', - * email: 'mona@github.com', - * location: 'San Francisco', - * members_allowed_repository_creation_type: 'all', - * members_can_create_repositories: true, - * name: 'github', - * twitter_username: 'github', - * }); - * ``` - */ - update(org, body = {}, options) { - return this._client.patch(path`/orgs/${org}`, { body, ...options }); - } - /** - * Deletes an organization and all its repositories. - * - * The organization login will be unavailable for 90 days after deletion. - * - * Please review the Terms of Service regarding account deletion before using this - * endpoint: - * - * https://docs.github.com/site-policy/github-terms/github-terms-of-service - * - * @example - * ```ts - * const org = await client.orgs.delete('org'); - * ``` - */ - delete(org, options) { - return this._client.delete(path`/orgs/${org}`, options); - } - /** - * List a collection of artifact attestations with a given subject digest that are - * associated with repositories owned by an organization. - * - * The collection of attestations returned by this endpoint is filtered according - * to the authenticated user's permissions; if the authenticated user cannot read a - * repository, the attestations associated with that repository will not be - * included in the response. In addition, when using a fine-grained access token - * the `attestations:read` permission is required. - * - * **Please note:** in order to offer meaningful security benefits, an - * attestation's signature and timestamps **must** be cryptographically verified, - * and the identity of the attestation signer **must** be validated. Attestations - * can be verified using the - * [GitHub CLI `attestation verify` command](https://cli.github.com/manual/gh_attestation_verify). - * For more information, see - * [our guide on how to use artifact attestations to establish a build's provenance](https://docs.github.com/actions/security-guides/using-artifact-attestations-to-establish-provenance-for-builds). - * - * @example - * ```ts - * const response = await client.orgs.listAttestations( - * 'subject_digest', - * { org: 'org' }, - * ); - * ``` - */ - listAttestations(subjectDigest, params, options) { - const { org, ...query } = params; - return this._client.get(path`/orgs/${org}/attestations/${subjectDigest}`, { query, ...options }); - } - /** - * > [!NOTE] This API is not built to serve real-time use cases. Depending on the - * > time of day, event latency can be anywhere from 30s to 6h. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const orgListEventsResponse of client.orgs.listEvents( - * 'org', - * )) { - * // ... - * } - * ``` - */ - listEvents(org, query = {}, options) { - return this._client.getAPIList(path`/orgs/${org}/events`, NumberedPage, { - query, - ...options - }); - } - /** - * The return hash contains `failed_at` and `failed_reason` fields which represent - * the time at which the invitation failed and the reason for the failure. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const orgListFailedInvitationsResponse of client.orgs.listFailedInvitations( - * 'org', - * )) { - * // ... - * } - * ``` - */ - listFailedInvitations(org, query = {}, options) { - return this._client.getAPIList(path`/orgs/${org}/failed_invitations`, NumberedPage, { query, ...options }); - } - /** - * Lists all GitHub Apps in an organization. The installation count includes all - * GitHub Apps installed on repositories in the organization. - * - * The authenticated user must be an organization owner to use this endpoint. - * - * OAuth app tokens and personal access tokens (classic) need the `admin:read` - * scope to use this endpoint. - * - * @example - * ```ts - * const response = await client.orgs.listInstallations('org'); - * ``` - */ - listInstallations(org, query = {}, options) { - return this._client.get(path`/orgs/${org}/installations`, { query, ...options }); - } - /** - * List issues in an organization assigned to the authenticated user. - * - * > [!NOTE] GitHub's REST API considers every pull request an issue, but not every - * > issue is a pull request. For this reason, "Issues" endpoints may return both - * > issues and pull requests in the response. You can identify pull requests by - * > the `pull_request` key. Be aware that the `id` of a pull request returned from - * > "Issues" endpoints will be an _issue id_. To find out the pull request id, use - * > the - * > "[List pull requests](https://docs.github.com/rest/pulls/pulls#list-pull-requests)" - * > endpoint. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response - * will include `body`. This is the default if you do not pass any specific media - * type. - * - **`application/vnd.github.text+json`**: Returns a text only representation of - * the markdown body. Response will include `body_text`. - * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's - * markdown. Response will include `body_html`. - * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML - * representations. Response will include `body`, `body_text`, and `body_html`. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const issue of client.orgs.listIssues('org')) { - * // ... - * } - * ``` - */ - listIssues(org, query = {}, options) { - return this._client.getAPIList(path`/orgs/${org}/issues`, NumberedPage, { - query, - ...options - }); - } - /** - * Lists repository security advisories for an organization. - * - * The authenticated user must be an owner or security manager for the organization - * to use this endpoint. - * - * OAuth app tokens and personal access tokens (classic) need the `repo` or - * `repository_advisories:write` scope to use this endpoint. - * - * @example - * ```ts - * const response = await client.orgs.listSecurityAdvisories( - * 'org', - * ); - * ``` - */ - listSecurityAdvisories(org, query = {}, options) { - return this._client.get(path`/orgs/${org}/security-advisories`, { query, ...options }); - } - /** - * Enables an authenticated GitHub App to find the organization's installation - * information. - * - * You must use a - * [JWT](https://docs.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) - * to access this endpoint. - * - * @example - * ```ts - * const installation = await client.orgs.retrieveInstallation( - * 'org', - * ); - * ``` - */ - retrieveInstallation(org, options) { - return this._client.get(path`/orgs/${org}/installation`, options); - } - } - BaseOrgs3._key = Object.freeze(["orgs"]); - return BaseOrgs3; -})(); - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/resources/search.mjs -var BaseSearch = /* @__PURE__ */ (() => { - class BaseSearch6 extends APIResource { - /** - * Searches for query terms inside of a file. This method returns up to 100 results - * [per page](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api). - * - * When searching for code, you can get text match metadata for the file - * **content** and file **path** fields when you pass the `text-match` media type. - * For more details about how to receive highlighted search results, see - * [Text match metadata](https://docs.github.com/rest/search/search#text-match-metadata). - * - * For example, if you want to find the definition of the `addClass` function - * inside [jQuery](https://github.com/jquery/jquery) repository, your query would - * look something like this: - * - * `q=addClass+in:file+language:js+repo:jquery/jquery` - * - * This query searches for the keyword `addClass` within a file's contents. The - * query limits the search to files where the language is JavaScript in the - * `jquery/jquery` repository. - * - * Considerations for code search: - * - * Due to the complexity of searching code, there are a few restrictions on how - * searches are performed: - * - * - Only the _default branch_ is considered. In most cases, this will be the - * `master` branch. - * - Only files smaller than 384 KB are searchable. - * - You must always include at least one search term when searching source code. - * For example, searching for - * [`language:go`](https://github.com/search?utf8=%E2%9C%93&q=language%3Ago&type=Code) - * is not valid, while - * [`amazing language:go`](https://github.com/search?utf8=%E2%9C%93&q=amazing+language%3Ago&type=Code) - * is. - * - * This endpoint requires you to authenticate and limits you to 10 requests per - * minute. - */ - codeSearch(query, options) { - return this._client.get("/search/code", { query, ...options }); - } - /** - * Find commits via various criteria on the default branch (usually `main`). This - * method returns up to 100 results - * [per page](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api). - * - * When searching for commits, you can get text match metadata for the **message** - * field when you provide the `text-match` media type. For more details about how - * to receive highlighted search results, see - * [Text match metadata](https://docs.github.com/rest/search/search#text-match-metadata). - * - * For example, if you want to find commits related to CSS in the - * [octocat/Spoon-Knife](https://github.com/octocat/Spoon-Knife) repository. Your - * query would look something like this: - * - * `q=repo:octocat/Spoon-Knife+css` - */ - commitSearch(query, options) { - return this._client.get("/search/commits", { query, ...options }); - } - /** - * > [!WARNING] > **Notice:** Search for issues and pull requests will be - * > overridden by advanced search on November 4, 2025. You can read more about - * > this change on - * > [the GitHub blog](https://github.blog/changelog/2025-03-06-github-issues-projects-api-support-for-issues-advanced-search-and-more/). - * - * @deprecated - */ - issueSearch(query, options) { - return this._client.get("/search/issues", { query, ...options }); - } - /** - * Find labels in a repository with names or descriptions that match search - * keywords. Returns up to 100 results - * [per page](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api). - * - * When searching for labels, you can get text match metadata for the label - * **name** and **description** fields when you pass the `text-match` media type. - * For more details about how to receive highlighted search results, see - * [Text match metadata](https://docs.github.com/rest/search/search#text-match-metadata). - * - * For example, if you want to find labels in the `linguist` repository that match - * `bug`, `defect`, or `enhancement`. Your query might look like this: - * - * `q=bug+defect+enhancement&repository_id=64778136` - * - * The labels that best match the query appear first in the search results. - */ - labelSearch(query, options) { - return this._client.get("/search/labels", { query, ...options }); - } - /** - * Find repositories via various criteria. This method returns up to 100 results - * [per page](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api). - * - * When searching for repositories, you can get text match metadata for the - * **name** and **description** fields when you pass the `text-match` media type. - * For more details about how to receive highlighted search results, see - * [Text match metadata](https://docs.github.com/rest/search/search#text-match-metadata). - * - * For example, if you want to search for popular Tetris repositories written in - * assembly code, your query might look like this: - * - * `q=tetris+language:assembly&sort=stars&order=desc` - * - * This query searches for repositories with the word `tetris` in the name, the - * description, or the README. The results are limited to repositories where the - * primary language is assembly. The results are sorted by stars in descending - * order, so that the most popular repositories appear first in the search results. - */ - repositorySearch(query, options) { - return this._client.get("/search/repositories", { query, ...options }); - } - /** - * Find topics via various criteria. Results are sorted by best match. This method - * returns up to 100 results - * [per page](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api). - * See "[Searching topics](https://docs.github.com/articles/searching-topics/)" for - * a detailed list of qualifiers. - * - * When searching for topics, you can get text match metadata for the topic's - * **short_description**, **description**, **name**, or **display_name** field when - * you pass the `text-match` media type. For more details about how to receive - * highlighted search results, see - * [Text match metadata](https://docs.github.com/rest/search/search#text-match-metadata). - * - * For example, if you want to search for topics related to Ruby that are featured - * on https://github.com/topics. Your query might look like this: - * - * `q=ruby+is:featured` - * - * This query searches for topics with the keyword `ruby` and limits the results to - * find only topics that are featured. The topics that are the best match for the - * query appear first in the search results. - */ - topicSearch(query, options) { - return this._client.get("/search/topics", { query, ...options }); - } - /** - * Find users via various criteria. This method returns up to 100 results - * [per page](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api). - * - * When searching for users, you can get text match metadata for the issue - * **login**, public **email**, and **name** fields when you pass the `text-match` - * media type. For more details about highlighting search results, see - * [Text match metadata](https://docs.github.com/rest/search/search#text-match-metadata). - * For more details about how to receive highlighted search results, see - * [Text match metadata](https://docs.github.com/rest/search/search#text-match-metadata). - * - * For example, if you're looking for a list of popular users, you might try this - * query: - * - * `q=tom+repos:%3E42+followers:%3E1000` - * - * This query searches for users with the name `tom`. The results are restricted to - * users with more than 42 repositories and over 1,000 followers. - * - * This endpoint does not accept authentication and will only include publicly - * visible users. As an alternative, you can use the GraphQL API. The GraphQL API - * requires authentication and will return private users, including Enterprise - * Managed Users (EMUs), that you are authorized to view. For more information, see - * "[GraphQL Queries](https://docs.github.com/graphql/reference/queries#search)." - */ - userSearch(query, options) { - return this._client.get("/search/users", { query, ...options }); + const text = await response.text(); + return text; + })(); + loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + body, + durationMs: Date.now() - startTime + })); + return body; +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/core/api-promise.mjs +var _APIPromise_client; +var APIPromise = class _APIPromise extends Promise { + constructor(client, responsePromise, parseResponse = defaultParseResponse) { + super((resolve) => { + resolve(null); + }); + this.responsePromise = responsePromise; + this.parseResponse = parseResponse; + _APIPromise_client.set(this, void 0); + __classPrivateFieldSet(this, _APIPromise_client, client, "f"); + } + _thenUnwrap(transform) { + return new _APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => transform(await this.parseResponse(client, props), props)); + } + /** + * Gets the raw `Response` instance instead of parsing the response + * data. + * + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + asResponse() { + return this.responsePromise.then((p) => p.response); + } + /** + * Gets the parsed response data and the raw `Response` instance. + * + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + async withResponse() { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { data, response }; + } + parse() { + if (!this.parsedPromise) { + this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data)); } + return this.parsedPromise; + } + then(onfulfilled, onrejected) { + return this.parse().then(onfulfilled, onrejected); + } + catch(onrejected) { + return this.parse().catch(onrejected); + } + finally(onfinally) { + return this.parse().finally(onfinally); } - BaseSearch6._key = Object.freeze(["search"]); - return BaseSearch6; -})(); -var Search = class extends BaseSearch { }; +_APIPromise_client = /* @__PURE__ */ new WeakMap(); -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/lib/secrets.mjs -var import_libsodium_wrappers = __toESM(require_libsodium_wrappers(), 1); - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/resources/repos/repos.mjs -var BaseRepos3 = /* @__PURE__ */ (() => { - class BaseRepos6 extends APIResource { - constructor() { - super(...arguments); - this._client_search = new Search(this._client); - this.search = { - codeSearch: (params, options) => { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params; - query.q = `repo:${owner}/${repo} ${query.q}`; - return this._client_search.codeSearch(query, options); - }, - commitSearch: (params, options) => { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params; - query.q = `repo:${owner}/${repo} ${query.q}`; - return this._client_search.commitSearch(query, options); - }, - issueSearch: (params, options) => { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params; - query.q = `repo:${owner}/${repo} ${query.q}`; - return this._client_search.issueSearch(query, options); - }, - labelSearch: (params, options) => { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params; - query.q = `repo:${owner}/${repo} ${query.q}`; - return this._client_search.labelSearch(query, options); - } - }; - } - /** - * Creates a new repository for the authenticated user. - * - * OAuth app tokens and personal access tokens (classic) need the `public_repo` or - * `repo` scope to create a public repository, and `repo` scope to create a private - * repository. - * - * @example - * ```ts - * const fullRepository = await client.repos.create({ - * name: 'Hello-World', - * description: 'This is your first repo!', - * homepage: 'https://github.com', - * is_template: true, - * }); - * ``` - */ - create(body, options) { - return this._client.post("/user/repos", { body, ...options }); - } - /** - * The `parent` and `source` objects are present when the repository is a fork. - * `parent` is the repository this repository was forked from, `source` is the - * ultimate source for the network. - * - * > [!NOTE] - * > - * > - In order to see the `security_and_analysis` block for a repository you must - * > have admin permissions for the repository or be an owner or security manager - * > for the organization that owns the repository. For more information, see - * > "[Managing security managers in your organization](https://docs.github.com/organizations/managing-peoples-access-to-your-organization-with-roles/managing-security-managers-in-your-organization)." - * > - To view merge-related settings, you must have the `contents:read` and - * > `contents:write` permissions. - * - * @example - * ```ts - * const fullRepository = await client.repos.retrieve({ - * owner: 'owner', - * repo: 'repo', - * }); - * ``` - */ - retrieve(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}`, options); - } - /** - * **Note**: To edit a repository's topics, use the - * [Replace all repository topics](https://docs.github.com/rest/repos/repos#replace-all-repository-topics) - * endpoint. - * - * @example - * ```ts - * const fullRepository = await client.repos.update({ - * owner: 'owner', - * repo: 'repo', - * description: 'This is your first repository', - * has_issues: true, - * has_projects: true, - * has_wiki: true, - * homepage: 'https://github.com', - * name: 'Hello-World', - * private: true, - * }); - * ``` - */ - update(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...body } = params ?? {}; - return this._client.patch(path`/repos/${owner}/${repo}`, { body, ...options }); +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/core/pagination.mjs +var _AbstractPage_client; +var AbstractPage = class { + constructor(client, response, body, options) { + _AbstractPage_client.set(this, void 0); + __classPrivateFieldSet(this, _AbstractPage_client, client, "f"); + this.options = options; + this.response = response; + this.body = body; + } + hasNextPage() { + const items = this.getPaginatedItems(); + if (!items.length) + return false; + return this.nextPageRequestOptions() != null; + } + async getNextPage() { + const nextOptions = this.nextPageRequestOptions(); + if (!nextOptions) { + throw new StainlessError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`."); } - /** - * Deleting a repository requires admin access. - * - * If an organization owner has configured the organization to prevent members from - * deleting organization-owned repositories, you will get a `403 Forbidden` - * response. - * - * OAuth app tokens and personal access tokens (classic) need the `delete_repo` - * scope to use this endpoint. - * - * @example - * ```ts - * await client.repos.delete({ owner: 'owner', repo: 'repo' }); - * ``` - */ - delete(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; - return this._client.delete(path`/repos/${owner}/${repo}`, { - ...options, - headers: buildHeaders([{ Accept: "*/*" }, options?.headers]) - }); + return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); + } + async *iterPages() { + let page = this; + yield page; + while (page.hasNextPage()) { + page = await page.getNextPage(); + yield page; } - /** - * Whether the authenticated user has starred the repository. - * - * @example - * ```ts - * await client.repos.checkStarred({ - * owner: 'owner', - * repo: 'repo', - * }); - * ``` - */ - checkStarred(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; - return this._client.get(path`/user/starred/${owner}/${repo}`, { - ...options, - headers: buildHeaders([{ Accept: "*/*" }, options?.headers]) - }); + } + async *[(_AbstractPage_client = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() { + for await (const page of this.iterPages()) { + for (const item of page.getPaginatedItems()) { + yield item; + } } - /** - * Compares two commits against one another. You can compare refs (branches or - * tags) and commit SHAs in the same repository, or you can compare refs and commit - * SHAs that exist in different repositories within the same repository network, - * including fork branches. For more information about how to view a repository's - * network, see - * "[Understanding connections between repositories](https://docs.github.com/repositories/viewing-activity-and-data-for-your-repository/understanding-connections-between-repositories)." - * - * This endpoint is equivalent to running the `git log BASE..HEAD` command, but it - * returns commits in a different order. The `git log BASE..HEAD` command returns - * commits in reverse chronological order, whereas the API returns commits in - * chronological order. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.diff`**: Returns the diff of the commit. - * - **`application/vnd.github.patch`**: Returns the patch of the commit. Diffs - * with binary data will have no `patch` property. - * - * The API response includes details about the files that were changed between the - * two commits. This includes the status of the change (if a file was added, - * removed, modified, or renamed), and details of the change itself. For example, - * files with a `renamed` status have a `previous_filename` field showing the - * previous filename of the file, and files with a `modified` status have a `patch` - * field showing the changes made to the file. - * - * When calling this endpoint without any paging parameter (`per_page` or `page`), - * the returned list is limited to 250 commits, and the last commit in the list is - * the most recent of the entire comparison. - * - * **Working with large comparisons** - * - * To process a response with a large number of commits, use a query parameter - * (`per_page` or `page`) to paginate the results. When using pagination: - * - * - The list of changed files is only shown on the first page of results, and it - * includes up to 300 changed files for the entire comparison. - * - The results are returned in chronological order, but the last commit in the - * returned list may not be the most recent one in the entire set if there are - * more pages of results. - * - * For more information on working with pagination, see - * "[Using pagination in the REST API](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api)." - * - * **Signature verification object** - * - * The response will include a `verification` object that describes the result of - * verifying the commit's signature. The `verification` object includes the - * following fields: - * - * | Name | Type | Description | - * | ------------- | --------- | ------------------------------------------------------------------------------------------------ | - * | `verified` | `boolean` | Indicates whether GitHub considers the signature in this commit to be verified. | - * | `reason` | `string` | The reason for verified value. Possible values and their meanings are enumerated in table below. | - * | `signature` | `string` | The signature that was extracted from the commit. | - * | `payload` | `string` | The value that was signed. | - * | `verified_at` | `string` | The date the signature was verified by GitHub. | - * - * These are the possible values for `reason` in the `verification` object: - * - * | Value | Description | - * | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------- | - * | `expired_key` | The key that made the signature is expired. | - * | `not_signing_key` | The "signing" flag is not among the usage flags in the GPG key that made the signature. | - * | `gpgverify_error` | There was an error communicating with the signature verification service. | - * | `gpgverify_unavailable` | The signature verification service is currently unavailable. | - * | `unsigned` | The object does not include a signature. | - * | `unknown_signature_type` | A non-PGP signature was found in the commit. | - * | `no_user` | No user was associated with the `committer` email address in the commit. | - * | `unverified_email` | The `committer` email address in the commit was associated with a user, but the email address is not verified on their account. | - * | `bad_email` | The `committer` email address in the commit is not included in the identities of the PGP key that made the signature. | - * | `unknown_key` | The key that made the signature has not been registered with any user's account. | - * | `malformed_signature` | There was an error parsing the signature. | - * | `invalid` | The signature could not be cryptographically verified using the key whose key-id was found in the signature. | - * | `valid` | None of the above errors applied, so the signature is considered to be verified. | - * - * @example - * ```ts - * const response = await client.repos.compareCommits( - * 'basehead', - * { owner: 'owner', repo: 'repo' }, - * ); - * ``` - */ - compareCommits(basehead, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/compare/${basehead}`, { query, ...options }); + } +}; +var PagePromise = class extends APIPromise { + constructor(client, request, Page2) { + super(client, request, async (client2, props) => new Page2(client2, props.response, await defaultParseResponse(client2, props), props.options)); + } + /** + * Allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ + async *[Symbol.asyncIterator]() { + const page = await this; + for await (const item of page) { + yield item; } - /** - * Users with push access in a repository can create commit statuses for a given - * SHA. - * - * Note: there is a limit of 1000 statuses per `sha` and `context` within a - * repository. Attempts to create more than 1000 statuses will result in a - * validation error. - * - * @example - * ```ts - * const response = await client.repos.createCommitStatus( - * 'sha', - * { - * owner: 'owner', - * repo: 'repo', - * state: 'success', - * context: 'continuous-integration/jenkins', - * description: 'The build succeeded!', - * target_url: 'https://example.com/build/status', - * }, - * ); - * ``` - */ - createCommitStatus(sha, params, options) { - const { owner = this._client.owner, repo = this._client.repo, ...body } = params; - return this._client.post(path`/repos/${owner}/${repo}/statuses/${sha}`, { body, ...options }); + } +}; +var Page = class extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.next_cursor = body.next_cursor || ""; + } + getPaginatedItems() { + return this.data ?? []; + } + nextPageRequestOptions() { + const cursor = this.next_cursor; + if (!cursor) { + return null; } - /** - * You can use this endpoint to trigger a webhook event called - * `repository_dispatch` when you want activity that happens outside of GitHub to - * trigger a GitHub Actions workflow or GitHub App webhook. You must configure your - * GitHub Actions workflow or GitHub App to run when the `repository_dispatch` - * event occurs. For an example `repository_dispatch` webhook payload, see - * "[RepositoryDispatchEvent](https://docs.github.com/webhooks/event-payloads/#repository_dispatch)." - * - * The `client_payload` parameter is available for any extra information that your - * workflow might need. This parameter is a JSON payload that will be passed on - * when the webhook event is dispatched. For example, the `client_payload` can - * include a message that a user would like to send using a GitHub Actions - * workflow. Or the `client_payload` can be used as a test to debug your workflow. - * - * This input example shows how you can use the `client_payload` as a test to debug - * your workflow. - * - * OAuth app tokens and personal access tokens (classic) need the `repo` scope to - * use this endpoint. - * - * @example - * ```ts - * await client.repos.createDispatchEvent({ - * owner: 'owner', - * repo: 'repo', - * event_type: 'on-demand-test', - * client_payload: { unit: false, integration: true }, - * }); - * ``` - */ - createDispatchEvent(params, options) { - const { owner = this._client.owner, repo = this._client.repo, ...body } = params; - return this._client.post(path`/repos/${owner}/${repo}/dispatches`, { - body, - ...options, - headers: buildHeaders([{ Accept: "*/*" }, options?.headers]) - }); + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + cursor + } + }; + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/uploads.mjs +var checkFileSupport = () => { + if (typeof File === "undefined") { + const { process: process7 } = globalThis; + const isOldNode = typeof process7?.versions?.node === "string" && parseInt(process7.versions.node.split(".")) < 20; + throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : "")); + } +}; +function makeFile(fileBits, fileName, options) { + checkFileSupport(); + return new File(fileBits, fileName ?? "unknown_file", options); +} +function getName(value) { + return (typeof value === "object" && value !== null && ("name" in value && value.name && String(value.name) || "url" in value && value.url && String(value.url) || "filename" in value && value.filename && String(value.filename) || "path" in value && value.path && String(value.path)) || "").split(/[\\/]/).pop() || void 0; +} +var isAsyncIterable = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function"; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/to-file.mjs +var isBlobLike = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function"; +var isFileLike = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value); +var isResponseLike = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function"; +async function toFile(value, name, options) { + checkFileSupport(); + value = await value; + if (isFileLike(value)) { + if (value instanceof File) { + return value; } - /** - * Creates a new repository in the specified organization. The authenticated user - * must be a member of the organization. - * - * OAuth app tokens and personal access tokens (classic) need the `public_repo` or - * `repo` scope to create a public repository, and `repo` scope to create a private - * repository. - * - * @example - * ```ts - * const fullRepository = await client.repos.createForOrg( - * 'org', - * { - * name: 'Hello-World', - * description: 'This is your first repository', - * has_issues: true, - * has_projects: true, - * has_wiki: true, - * homepage: 'https://github.com', - * }, - * ); - * ``` - */ - createForOrg(org, body, options) { - return this._client.post(path`/orgs/${org}/repos`, { body, ...options }); + return makeFile([await value.arrayBuffer()], value.name); + } + if (isResponseLike(value)) { + const blob = await value.blob(); + name || (name = new URL(value.url).pathname.split(/[\\/]/).pop()); + return makeFile(await getBytes(blob), name, options); + } + const parts = await getBytes(value); + name || (name = getName(value)); + if (!options?.type) { + const type = parts.find((part) => typeof part === "object" && "type" in part && part.type); + if (typeof type === "string") { + options = { ...options, type }; } - /** - * Creates a new repository using a repository template. Use the `template_owner` - * and `template_repo` route parameters to specify the repository to use as the - * template. If the repository is not public, the authenticated user must own or be - * a member of an organization that owns the repository. To check if a repository - * is available to use as a template, get the repository's information using the - * [Get a repository](https://docs.github.com/rest/repos/repos#get-a-repository) - * endpoint and check that the `is_template` key is `true`. - * - * OAuth app tokens and personal access tokens (classic) need the `public_repo` or - * `repo` scope to create a public repository, and `repo` scope to create a private - * repository. - * - * @example - * ```ts - * const fullRepository = - * await client.repos.createFromTemplate('template_repo', { - * template_owner: 'template_owner', - * name: 'Hello-World', - * description: 'This is your first repository', - * owner: 'octocat', - * }); - * ``` - */ - createFromTemplate(templateRepo, params, options) { - const { template_owner, ...body } = params; - return this._client.post(path`/repos/${template_owner}/${templateRepo}/generate`, { body, ...options }); + } + return makeFile(parts, name, options); +} +async function getBytes(value) { + let parts = []; + if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. + value instanceof ArrayBuffer) { + parts.push(value); + } else if (isBlobLike(value)) { + parts.push(value instanceof Blob ? value : await value.arrayBuffer()); + } else if (isAsyncIterable(value)) { + for await (const chunk of value) { + parts.push(...await getBytes(chunk)); } - /** - * Gets a redirect URL to download a tar archive for a repository. If you omit - * `:ref`, the repository’s default branch (usually `main`) will be used. Please - * make sure your HTTP framework is configured to follow redirects or you will need - * to use the `Location` header to make a second `GET` request. - * - * > [!NOTE] For private repositories, these links are temporary and expire after - * > five minutes. - * - * @example - * ```ts - * await client.repos.downloadTarball('ref', { - * owner: 'owner', - * repo: 'repo', - * }); - * ``` - */ - downloadTarball(ref, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/tarball/${ref}`, { - ...options, - headers: buildHeaders([{ Accept: "*/*" }, options?.headers]) + } else { + const constructor = value?.constructor?.name; + throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError(value)}`); + } + return parts; +} +function propsForError(value) { + if (typeof value !== "object" || value === null) + return ""; + const props = Object.getOwnPropertyNames(value); + return `; props: [${props.map((p) => `"${p}"`).join(", ")}]`; +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/core/resource.mjs +var APIResource = class { + constructor(client) { + this._client = client; + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/path.mjs +function encodeURIPath(str) { + return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); +} +var EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); +var createPathTagFunction = (pathEncoder = encodeURIPath) => function path7(statics, ...params) { + if (statics.length === 1) + return statics[0]; + let postPath = false; + const invalidSegments = []; + const path8 = statics.reduce((previousValue, currentValue, index) => { + if (/[?#]/.test(currentValue)) { + postPath = true; + } + const value = params[index]; + let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value); + if (index !== params.length && (value == null || typeof value === "object" && // handle values from other realms + value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY)?.toString)) { + encoded = value + ""; + invalidSegments.push({ + start: previousValue.length + currentValue.length, + length: encoded.length, + error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter` }); } - /** - * Gets a redirect URL to download a zip archive for a repository. If you omit - * `:ref`, the repository’s default branch (usually `main`) will be used. Please - * make sure your HTTP framework is configured to follow redirects or you will need - * to use the `Location` header to make a second `GET` request. - * - * > [!NOTE] For private repositories, these links are temporary and expire after - * > five minutes. If the repository is empty, you will receive a 404 when you - * > follow the redirect. - * - * @example - * ```ts - * await client.repos.downloadZipball('ref', { - * owner: 'owner', - * repo: 'repo', - * }); - * ``` - */ - downloadZipball(ref, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/zipball/${ref}`, { - ...options, - headers: buildHeaders([{ Accept: "*/*" }, options?.headers]) - }); + return previousValue + currentValue + (index === params.length ? "" : encoded); + }, ""); + const pathOnly = path8.split(/[?#]/, 1)[0]; + const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; + let match; + while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) { + invalidSegments.push({ + start: match.index, + length: match[0].length, + error: `Value "${match[0]}" can't be safely passed as a path parameter` + }); + } + invalidSegments.sort((a, b) => a.start - b.start); + if (invalidSegments.length > 0) { + let lastEnd = 0; + const underline = invalidSegments.reduce((acc, segment) => { + const spaces = " ".repeat(segment.start - lastEnd); + const arrows = "^".repeat(segment.length); + lastEnd = segment.start + segment.length; + return acc + spaces + arrows; + }, ""); + throw new StainlessError(`Path parameters result in path with invalid segments: +${invalidSegments.map((e) => e.error).join("\n")} +${path8} +${underline}`); + } + return path8; +}; +var path = /* @__PURE__ */ createPathTagFunction(encodeURIPath); + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/builds/diagnostics.mjs +var Diagnostics = class extends APIResource { + /** + * Get the list of diagnostics for a given build. + * + * If no language targets are specified, diagnostics for all languages are + * returned. + */ + list(buildID, query = {}, options) { + return this._client.getAPIList(path`/v0/builds/${buildID}/diagnostics`, Page, { + query, + ...options + }); + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/builds/target-outputs.mjs +var TargetOutputs = class extends APIResource { + /** + * Retrieve a method to download an output for a given build target. + * + * If the requested type of output is `source`, and the requested output method is + * `url`, a download link to a tarball of the source files is returned. If the + * requested output method is `git`, a Git remote, ref, and access token (if + * necessary) is returned. + * + * Otherwise, the possible types of outputs are specific to the requested target, + * and the output method _must_ be `url`. See the documentation for `type` for more + * information. + */ + retrieve(query, options) { + return this._client.get("/v0/build_target_outputs", { query, ...options }); + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/builds/builds.mjs +var Builds = class extends APIResource { + constructor() { + super(...arguments); + this.diagnostics = new Diagnostics(this._client); + this.targetOutputs = new TargetOutputs(this._client); + } + /** + * Create a build, on top of a project branch, against a given input revision. + * + * The project branch will be modified so that its latest set of config files + * points to the one specified by the input revision. + */ + create(params, options) { + const { project = this._client.project, ...body } = params; + return this._client.post("/v0/builds", { body: { project, ...body }, ...options }); + } + /** + * Retrieve a build by its ID. + */ + retrieve(buildID, options) { + return this._client.get(path`/v0/builds/${buildID}`, options); + } + /** + * List user-triggered builds for a given project. + * + * An optional revision can be specified to filter by config commit SHA, or hashes + * of file contents. + */ + list(params = {}, options) { + const { project = this._client.project, ...query } = params ?? {}; + return this._client.getAPIList("/v0/builds", Page, { query: { project, ...query }, ...options }); + } + /** + * Create two builds whose outputs can be directly compared with each other. + * + * Created builds _modify_ their project branches so that their latest sets of + * config files point to the ones specified by the input revision. + * + * This endpoint is useful because a build has more inputs than the set of config + * files it uses, so comparing two builds directly may return spurious differences. + * Builds made via this endpoint are guaranteed to have differences arising from + * the set of config files, and any custom code. + */ + compare(params, options) { + const { project = this._client.project, ...body } = params; + return this._client.post("/v0/builds/compare", { body: { project, ...body }, ...options }); + } +}; +Builds.Diagnostics = Diagnostics; +Builds.TargetOutputs = TargetOutputs; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/orgs.mjs +var Orgs = class extends APIResource { + /** + * Retrieve an organization by name. + */ + retrieve(org, options) { + return this._client.get(path`/v0/orgs/${org}`, options); + } + /** + * List organizations accessible to the current authentication method. + */ + list(options) { + return this._client.get("/v0/orgs", options); + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/projects/branches.mjs +var Branches = class extends APIResource { + /** + * Create a new branch for a project. + * + * The branch inherits the config files from the revision pointed to by the + * `branch_from` parameter. In addition, if the revision is a branch name, the + * branch will also inherit custom code changes from that branch. + */ + create(params, options) { + const { project = this._client.project, ...body } = params; + return this._client.post(path`/v0/projects/${project}/branches`, { body, ...options }); + } + /** + * Retrieve a project branch by name. + */ + retrieve(branch, params = {}, options) { + const { project = this._client.project } = params ?? {}; + return this._client.get(path`/v0/projects/${project}/branches/${branch}`, options); + } + /** + * Retrieve a project branch by name. + */ + list(params = {}, options) { + const { project = this._client.project, ...query } = params ?? {}; + return this._client.getAPIList(path`/v0/projects/${project}/branches`, Page, { + query, + ...options + }); + } + /** + * Delete a project branch by name. + */ + delete(branch, params = {}, options) { + const { project = this._client.project } = params ?? {}; + return this._client.delete(path`/v0/projects/${project}/branches/${branch}`, options); + } + /** + * Rebase a project branch. + * + * The branch is rebased onto the `base` branch or commit SHA, inheriting any + * config and custom code changes. + */ + rebase(branch, params = {}, options) { + const { project = this._client.project, base } = params ?? {}; + return this._client.put(path`/v0/projects/${project}/branches/${branch}/rebase`, { + query: { base }, + ...options + }); + } + /** + * Reset a project branch. + * + * If `branch` === `main`, the branch is reset to `target_config_sha`. Otherwise, + * the branch is reset to `main`. + */ + reset(branch, params = {}, options) { + const { project = this._client.project, target_config_sha } = params ?? {}; + return this._client.put(path`/v0/projects/${project}/branches/${branch}/reset`, { + query: { target_config_sha }, + ...options + }); + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/projects/configs.mjs +var Configs = class extends APIResource { + /** + * Retrieve the configuration files for a given project. + */ + retrieve(params = {}, options) { + const { project = this._client.project, ...query } = params ?? {}; + return this._client.get(path`/v0/projects/${project}/configs`, { query, ...options }); + } + /** + * Generate suggestions for changes to config files based on an OpenAPI spec. + */ + guess(params, options) { + const { project = this._client.project, ...body } = params; + return this._client.post(path`/v0/projects/${project}/configs/guess`, { body, ...options }); + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/projects/projects.mjs +var Projects = class extends APIResource { + constructor() { + super(...arguments); + this.branches = new Branches(this._client); + this.configs = new Configs(this._client); + } + /** + * Create a new project. + */ + create(body, options) { + return this._client.post("/v0/projects", { body, ...options }); + } + /** + * Retrieve a project by name. + */ + retrieve(params = {}, options) { + const { project = this._client.project } = params ?? {}; + return this._client.get(path`/v0/projects/${project}`, options); + } + /** + * Update a project's properties. + */ + update(params = {}, options) { + const { project = this._client.project, ...body } = params ?? {}; + return this._client.patch(path`/v0/projects/${project}`, { body, ...options }); + } + /** + * List projects in an organization, from oldest to newest. + */ + list(query = {}, options) { + return this._client.getAPIList("/v0/projects", Page, { query, ...options }); + } + /** + * Generates an AI commit message by comparing two git refs in the SDK repository. + */ + generateCommitMessage(params, options) { + const { project = this._client.project, target, ...body } = params; + return this._client.post(path`/v0/projects/${project}/generate_commit_message`, { + query: { target }, + body, + ...options + }); + } +}; +Projects.Branches = Branches; +Projects.Configs = Configs; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/user.mjs +var User = class extends APIResource { + /** + * Retrieve the currently authenticated user's information. + */ + retrieve(options) { + return this._client.get("/v0/user", options); + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/headers.mjs +var brand_privateNullableHeaders = /* @__PURE__ */ Symbol("brand.privateNullableHeaders"); +function* iterateHeaders(headers) { + if (!headers) + return; + if (brand_privateNullableHeaders in headers) { + const { values, nulls } = headers; + yield* values.entries(); + for (const name of nulls) { + yield [name, null]; + } + return; + } + let shouldClear = false; + let iter; + if (headers instanceof Headers) { + iter = headers.entries(); + } else if (isReadonlyArray(headers)) { + iter = headers; + } else { + shouldClear = true; + iter = Object.entries(headers ?? {}); + } + for (let row of iter) { + const name = row[0]; + if (typeof name !== "string") + throw new TypeError("expected header name to be a string"); + const values = isReadonlyArray(row[1]) ? row[1] : [row[1]]; + let didClear = false; + for (const value of values) { + if (value === void 0) + continue; + if (shouldClear && !didClear) { + didClear = true; + yield [name, null]; + } + yield [name, value]; } - /** - * Enables an authenticated GitHub App to find the repository's installation - * information. The installation's account type will be either an organization or a - * user account, depending which account the repository belongs to. - * - * You must use a - * [JWT](https://docs.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) - * to access this endpoint. - * - * @example - * ```ts - * const installation = await client.repos.getInstallationInfo( - * { owner: 'owner', repo: 'repo' }, - * ); - * ``` - */ - getInstallationInfo(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/installation`, options); + } +} +var buildHeaders = (newHeaders) => { + const targetHeaders = new Headers(); + const nullHeaders = /* @__PURE__ */ new Set(); + for (const headers of newHeaders) { + const seenHeaders = /* @__PURE__ */ new Set(); + for (const [name, value] of iterateHeaders(headers)) { + const lowerName = name.toLowerCase(); + if (!seenHeaders.has(lowerName)) { + targetHeaders.delete(name); + seenHeaders.add(lowerName); + } + if (value === null) { + targetHeaders.delete(name); + nullHeaders.add(lowerName); + } else { + targetHeaders.append(name, value); + nullHeaders.delete(lowerName); + } } - /** - * This method returns the contents of the repository's license file, if one is - * detected. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.raw+json`**: Returns the raw contents of the - * license. - * - **`application/vnd.github.html+json`**: Returns the license contents in HTML. - * Markup languages are rendered to HTML using GitHub's open-source - * [Markup library](https://github.com/github/markup). - * - * @example - * ```ts - * const response = await client.repos.getLicense({ - * owner: 'owner', - * repo: 'repo', - * }); - * ``` - */ - getLicense(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/license`, { query, ...options }); + } + return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders }; +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/env.mjs +var readEnv = (env) => { + if (typeof globalThis.process !== "undefined") { + return globalThis.process.env?.[env]?.trim() ?? void 0; + } + if (typeof globalThis.Deno !== "undefined") { + return globalThis.Deno.env?.get?.(env)?.trim(); + } + return void 0; +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/lib/unwrap.mjs +async function unwrapFile(value) { + if (value === null) { + return null; + } + if (value.type === "content") { + return value.content; + } + const response = await fetch(value.url); + return response.text(); +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/client.mjs +var _Stainless_instances; +var _a; +var _Stainless_encoder; +var _Stainless_baseURLOverridden; +var environments = { + production: "https://api.stainless.com", + staging: "https://staging.stainless.com" +}; +var Stainless = class { + /** + * API Client for interfacing with the Stainless API. + * + * @param {string | null | undefined} [opts.apiKey=process.env['STAINLESS_API_KEY'] ?? null] + * @param {string | null | undefined} [opts.project] + * @param {Environment} [opts.environment=production] - Specifies the environment URL to use for the API. + * @param {string} [opts.baseURL=process.env['STAINLESS_BASE_URL'] ?? https://api.stainless.com] - Override the default base URL for the API. + * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. + * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. + */ + constructor({ baseURL = readEnv("STAINLESS_BASE_URL"), apiKey = readEnv("STAINLESS_API_KEY") ?? null, project = null, ...opts } = {}) { + _Stainless_instances.add(this); + _Stainless_encoder.set(this, void 0); + this.projects = new Projects(this); + this.builds = new Builds(this); + this.orgs = new Orgs(this); + this.user = new User(this); + const options = { + apiKey, + project, + ...opts, + baseURL, + environment: opts.environment ?? "production" + }; + if (baseURL && opts.environment) { + throw new StainlessError("Ambiguous URL; The `baseURL` option (or STAINLESS_BASE_URL env var) and the `environment` option are given. If you want to use the environment you must pass baseURL: null"); } - /** - * Get the code security configuration that manages a repository's code security - * settings. - * - * The authenticated user must be an administrator or security manager for the - * organization to use this endpoint. - * - * OAuth app tokens and personal access tokens (classic) need the `repo` scope to - * use this endpoint. - * - * @example - * ```ts - * const response = - * await client.repos.getSecurityConfiguration({ - * owner: 'owner', - * repo: 'repo', - * }); - * ``` - */ - getSecurityConfiguration(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/code-security-configuration`, options); + this.baseURL = options.baseURL || environments[options.environment || "production"]; + this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT; + this.logger = options.logger ?? console; + const defaultLogLevel = "warn"; + this.logLevel = defaultLogLevel; + this.logLevel = parseLogLevel(options.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel(readEnv("STAINLESS_LOG"), "process.env['STAINLESS_LOG']", this) ?? defaultLogLevel; + this.fetchOptions = options.fetchOptions; + this.maxRetries = options.maxRetries ?? 2; + this.fetch = options.fetch ?? getDefaultFetch(); + __classPrivateFieldSet(this, _Stainless_encoder, FallbackEncoder, "f"); + this._options = options; + this.apiKey = apiKey; + this.project = project; + } + /** + * Create a new client instance re-using the same options given to the current client with optional overriding. + */ + withOptions(options) { + const client = new this.constructor({ + ...this._options, + environment: options.environment ? options.environment : void 0, + baseURL: options.environment ? void 0 : this.baseURL, + maxRetries: this.maxRetries, + timeout: this.timeout, + logger: this.logger, + logLevel: this.logLevel, + fetch: this.fetch, + fetchOptions: this.fetchOptions, + apiKey: this.apiKey, + project: this.project, + ...options + }); + return client; + } + defaultQuery() { + return this._options.defaultQuery; + } + validateHeaders({ values, nulls }) { + if (this.apiKey && values.get("authorization")) { + return; } - /** - * Lists a detailed history of changes to a repository, such as pushes, merges, - * force pushes, and branch changes, and associates these changes with commits and - * users. - * - * For more information about viewing repository activity, see - * "[Viewing activity and data for your repository](https://docs.github.com/repositories/viewing-activity-and-data-for-your-repository)." - * - * @example - * ```ts - * const response = await client.repos.listActivity({ - * owner: 'owner', - * repo: 'repo', - * }); - * ``` - */ - listActivity(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/activity`, { query, ...options }); + if (nulls.has("authorization")) { + return; } - /** - * > [!NOTE] This API is not built to serve real-time use cases. Depending on the - * > time of day, event latency can be anywhere from 30s to 6h. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const repoListEventsResponse of client.repos.listEvents( - * { owner: 'owner', repo: 'repo' }, - * )) { - * // ... - * } - * ``` - */ - listEvents(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.getAPIList(path`/repos/${owner}/${repo}/events`, NumberedPage, { query, ...options }); + throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "Authorization" headers to be explicitly omitted'); + } + async authHeaders(opts) { + if (this.apiKey == null) { + return void 0; } - /** - * Lists repositories that the authenticated user has explicit permission (`:read`, - * `:write`, or `:admin`) to access. - * - * The authenticated user has explicit permission to access repositories they own, - * repositories where they are a collaborator, and repositories that they can - * access through an organization membership. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const repository of client.repos.listForCurrentUser()) { - * // ... - * } - * ``` - */ - listForCurrentUser(query = {}, options) { - return this._client.getAPIList("/user/repos", NumberedPage, { query, ...options }); + return buildHeaders([{ Authorization: `Bearer ${this.apiKey}` }]); + } + stringifyQuery(query) { + return stringifyQuery(query); + } + getUserAgent() { + return `${this.constructor.name}/JS ${VERSION}`; + } + defaultIdempotencyKey() { + return `stainless-node-retry-${uuid4()}`; + } + makeStatusError(status, error, message, headers) { + return APIError.generate(status, error, message, headers); + } + buildURL(path7, query, defaultBaseURL) { + const baseURL = !__classPrivateFieldGet(this, _Stainless_instances, "m", _Stainless_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL; + const url = isAbsoluteURL(path7) ? new URL(path7) : new URL(baseURL + (baseURL.endsWith("/") && path7.startsWith("/") ? path7.slice(1) : path7)); + const defaultQuery = this.defaultQuery(); + if (!isEmptyObj(defaultQuery)) { + query = { ...defaultQuery, ...query }; } - /** - * Lists repositories for the specified organization. - * - * > [!NOTE] In order to see the `security_and_analysis` block for a repository you - * > must have admin permissions for the repository or be an owner or security - * > manager for the organization that owns the repository. For more information, - * > see - * > "[Managing security managers in your organization](https://docs.github.com/organizations/managing-peoples-access-to-your-organization-with-roles/managing-security-managers-in-your-organization)." - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const minimalRepository of client.repos.listForOrg( - * 'org', - * )) { - * // ... - * } - * ``` - */ - listForOrg(org, query = {}, options) { - return this._client.getAPIList(path`/orgs/${org}/repos`, NumberedPage, { - query, - ...options - }); + if (typeof query === "object" && query && !Array.isArray(query)) { + url.search = this.stringifyQuery(query); } - /** - * Lists public repositories for the specified user. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const minimalRepository of client.repos.listForUser( - * 'username', - * )) { - * // ... - * } - * ``` - */ - listForUser(username, query = {}, options) { - return this._client.getAPIList(path`/users/${username}/repos`, NumberedPage, { - query, - ...options - }); + return url.toString(); + } + /** + * Used as a callback for mutating the given `FinalRequestOptions` object. + */ + async prepareOptions(options) { + } + /** + * Used as a callback for mutating the given `RequestInit` object. + * + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. + */ + async prepareRequest(request, { url, options }) { + } + get(path7, opts) { + return this.methodRequest("get", path7, opts); + } + post(path7, opts) { + return this.methodRequest("post", path7, opts); + } + patch(path7, opts) { + return this.methodRequest("patch", path7, opts); + } + put(path7, opts) { + return this.methodRequest("put", path7, opts); + } + delete(path7, opts) { + return this.methodRequest("delete", path7, opts); + } + methodRequest(method, path7, opts) { + return this.request(Promise.resolve(opts).then((opts2) => { + return { method, path: path7, ...opts2 }; + })); + } + request(options, remainingRetries = null) { + return new APIPromise(this, this.makeRequest(options, remainingRetries, void 0)); + } + async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { + const options = await optionsInput; + const maxRetries = options.maxRetries ?? this.maxRetries; + if (retriesRemaining == null) { + retriesRemaining = maxRetries; } - /** - * Lists all public repositories in the order that they were created. - * - * Note: - * - * - For GitHub Enterprise Server, this endpoint will only list repositories - * available to all users on the enterprise. - * - Pagination is powered exclusively by the `since` parameter. Use the - * [Link header](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api#using-link-headers) - * to get the URL for the next page of repositories. - * - * @example - * ```ts - * const minimalRepositories = await client.repos.listPublic(); - * ``` - */ - listPublic(query = {}, options) { - return this._client.get("/repositories", { query, ...options }); + await this.prepareOptions(options); + const { req, url, timeout } = await this.buildRequest(options, { + retryCount: maxRetries - retriesRemaining + }); + await this.prepareRequest(req, { url, options }); + const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0"); + const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`; + const startTime = Date.now(); + loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({ + retryOfRequestLogID, + method: options.method, + url, + options, + headers: req.headers + })); + if (options.signal?.aborted) { + throw new APIUserAbortError(); } - /** - * Lists the people that have starred the repository. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.star+json`**: Includes a timestamp of when the star - * was created. - * - * @example - * ```ts - * const response = await client.repos.listStargazers({ - * owner: 'owner', - * repo: 'repo', - * }); - * ``` - */ - listStargazers(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/stargazers`, { query, ...options }); + const controller = new AbortController(); + const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError); + const headersTime = Date.now(); + if (response instanceof globalThis.Error) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + if (options.signal?.aborted) { + throw new APIUserAbortError(); + } + const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : "")); + if (retriesRemaining) { + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`); + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); + } + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`); + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + if (isTimeout) { + throw new APIConnectionTimeoutError(); + } + throw new APIConnectionError({ cause: response }); } - /** - * Lists repositories the authenticated user has starred. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.star+json`**: Includes a timestamp of when the star - * was created. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const repository of client.repos.listStarred()) { - * // ... - * } - * ``` - */ - listStarred(query = {}, options) { - return this._client.getAPIList("/user/starred", NumberedPage, { query, ...options }); + const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`; + if (!response.ok) { + const shouldRetry = await this.shouldRetry(response); + if (retriesRemaining && shouldRetry) { + const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`; + await CancelReadableStream(response.body); + loggerFor(this).info(`${responseInfo} - ${retryMessage2}`); + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); + } + const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; + loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + const errText = await response.text().catch((err2) => castToError(err2).message); + const errJSON = safeJSON(errText); + const errMessage = errJSON ? void 0 : errText; + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + message: errMessage, + durationMs: Date.now() - startTime + })); + const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); + throw err; } - /** - * Lists the people watching the specified repository. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const simpleUser of client.repos.listWatchers({ - * owner: 'owner', - * repo: 'repo', - * })) { - * // ... - * } - * ``` - */ - listWatchers(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.getAPIList(path`/repos/${owner}/${repo}/subscribers`, NumberedPage, { query, ...options }); + loggerFor(this).info(responseInfo); + loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; + } + getAPIList(path7, Page2, opts) { + return this.requestAPIList(Page2, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path7, ...opts2 })) : { method: "get", path: path7, ...opts }); + } + requestAPIList(Page2, options) { + const request = this.makeRequest(options, null, void 0); + return new PagePromise(this, request, Page2); + } + async fetchWithTimeout(url, init, ms, controller) { + const { signal, method, ...options } = init || {}; + const abort = this._makeAbort(controller); + if (signal) + signal.addEventListener("abort", abort, { once: true }); + const timeout = setTimeout(abort, ms); + const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body; + const fetchOptions = { + signal: controller.signal, + ...isReadableBody ? { duplex: "half" } : {}, + method: "GET", + ...options + }; + if (method) { + fetchOptions.method = method.toUpperCase(); } - /** - * Merge a branch - * - * @example - * ```ts - * const commit = await client.repos.mergeBranch({ - * owner: 'owner', - * repo: 'repo', - * base: 'master', - * head: 'cool_feature', - * commit_message: 'Shipped cool_feature!', - * }); - * ``` - */ - mergeBranch(params, options) { - const { owner = this._client.owner, repo = this._client.repo, ...body } = params; - return this._client.post(path`/repos/${owner}/${repo}/merges`, { body, ...options }); + try { + return await this.fetch.call(void 0, url, fetchOptions); + } finally { + clearTimeout(timeout); } - /** - * Note that you'll need to set `Content-Length` to zero when calling out to this - * endpoint. For more information, see - * "[HTTP method](https://docs.github.com/rest/guides/getting-started-with-the-rest-api#http-method)." - * - * @example - * ```ts - * await client.repos.star({ owner: 'owner', repo: 'repo' }); - * ``` - */ - star(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; - return this._client.put(path`/user/starred/${owner}/${repo}`, { - ...options, - headers: buildHeaders([{ Accept: "*/*" }, options?.headers]) - }); + } + async shouldRetry(response) { + const shouldRetryHeader = response.headers.get("x-should-retry"); + if (shouldRetryHeader === "true") + return true; + if (shouldRetryHeader === "false") + return false; + if (response.status === 408) + return true; + if (response.status === 409) + return true; + if (response.status === 429) + return true; + if (response.status >= 500) + return true; + return false; + } + async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { + let timeoutMillis; + const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms"); + if (retryAfterMillisHeader) { + const timeoutMs = parseFloat(retryAfterMillisHeader); + if (!Number.isNaN(timeoutMs)) { + timeoutMillis = timeoutMs; + } } - /** - * Sync a branch of a forked repository to keep it up-to-date with the upstream - * repository. - * - * @example - * ```ts - * const response = await client.repos.syncFork({ - * owner: 'owner', - * repo: 'repo', - * branch: 'main', - * }); - * ``` - */ - syncFork(params, options) { - const { owner = this._client.owner, repo = this._client.repo, ...body } = params; - return this._client.post(path`/repos/${owner}/${repo}/merge-upstream`, { body, ...options }); + const retryAfterHeader = responseHeaders?.get("retry-after"); + if (retryAfterHeader && !timeoutMillis) { + const timeoutSeconds = parseFloat(retryAfterHeader); + if (!Number.isNaN(timeoutSeconds)) { + timeoutMillis = timeoutSeconds * 1e3; + } else { + timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); + } } - /** - * A transfer request will need to be accepted by the new owner when transferring a - * personal repository to another user. The response will contain the original - * `owner`, and the transfer will continue asynchronously. For more details on the - * requirements to transfer personal and organization-owned repositories, see - * [about repository transfers](https://docs.github.com/articles/about-repository-transfers/). - * - * @example - * ```ts - * const minimalRepository = await client.repos.transfer({ - * owner: 'owner', - * repo: 'repo', - * new_owner: 'github', - * new_name: 'octorepo', - * team_ids: [12, 345], - * }); - * ``` - */ - transfer(params, options) { - const { owner = this._client.owner, repo = this._client.repo, ...body } = params; - return this._client.post(path`/repos/${owner}/${repo}/transfer`, { body, ...options }); + if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1e3)) { + const maxRetries = options.maxRetries ?? this.maxRetries; + timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); } - /** - * Unstar a repository that the authenticated user has previously starred. - * - * @example - * ```ts - * await client.repos.unstar({ owner: 'owner', repo: 'repo' }); - * ``` - */ - unstar(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; - return this._client.delete(path`/user/starred/${owner}/${repo}`, { - ...options, - headers: buildHeaders([{ Accept: "*/*" }, options?.headers]) - }); + await sleep(timeoutMillis); + return this.makeRequest(options, retriesRemaining - 1, requestLogID); + } + calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { + const initialRetryDelay = 0.5; + const maxRetryDelay = 8; + const numRetries = maxRetries - retriesRemaining; + const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); + const jitter = 1 - Math.random() * 0.25; + return sleepSeconds * jitter * 1e3; + } + async buildRequest(inputOptions, { retryCount = 0 } = {}) { + const options = { ...inputOptions }; + const { method, path: path7, query, defaultBaseURL } = options; + const url = this.buildURL(path7, query, defaultBaseURL); + if ("timeout" in options) + validatePositiveInteger("timeout", options.timeout); + options.timeout = options.timeout ?? this.timeout; + const { bodyHeaders, body } = this.buildBody({ options }); + const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); + const req = { + method, + headers: reqHeaders, + ...options.signal && { signal: options.signal }, + ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" }, + ...body && { body }, + ...this.fetchOptions ?? {}, + ...options.fetchOptions ?? {} + }; + return { req, url, timeout: options.timeout }; + } + async buildHeaders({ options, method, bodyHeaders, retryCount }) { + let idempotencyHeaders = {}; + if (this.idempotencyHeader && method !== "get") { + if (!options.idempotencyKey) + options.idempotencyKey = this.defaultIdempotencyKey(); + idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; } + const headers = buildHeaders([ + idempotencyHeaders, + { + Accept: "application/json", + "User-Agent": this.getUserAgent(), + "X-Stainless-Retry-Count": String(retryCount), + ...options.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options.timeout / 1e3)) } : {}, + ...getPlatformHeaders() + }, + await this.authHeaders(options), + this._options.defaultHeaders, + bodyHeaders, + options.headers + ]); + this.validateHeaders(headers); + return headers.values; } - BaseRepos6._key = Object.freeze(["repos"]); - return BaseRepos6; -})(); - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/utils/env.mjs -var readEnv = (env) => { - if (typeof globalThis.process !== "undefined") { - return globalThis.process.env?.[env]?.trim() ?? void 0; + _makeAbort(controller) { + return () => controller.abort(); } - if (typeof globalThis.Deno !== "undefined") { - return globalThis.Deno.env?.get?.(env)?.trim(); + buildBody({ options: { body, headers: rawHeaders } }) { + if (!body) { + return { bodyHeaders: void 0, body: void 0 }; + } + const headers = buildHeaders([rawHeaders]); + if ( + // Pass raw type verbatim + ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && // Preserve legacy string encoding behavior for now + headers.values.has("content-type") || // `Blob` is superset of `File` + globalThis.Blob && body instanceof globalThis.Blob || // `FormData` -> `multipart/form-data` + body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded` + body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`) + globalThis.ReadableStream && body instanceof globalThis.ReadableStream + ) { + return { bodyHeaders: void 0, body }; + } else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) { + return { bodyHeaders: void 0, body: ReadableStreamFrom(body) }; + } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") { + return { + bodyHeaders: { "content-type": "application/x-www-form-urlencoded" }, + body: this.stringifyQuery(body) + }; + } else { + return __classPrivateFieldGet(this, _Stainless_encoder, "f").call(this, { body, headers }); + } } - return void 0; }; +_a = Stainless, _Stainless_encoder = /* @__PURE__ */ new WeakMap(), _Stainless_instances = /* @__PURE__ */ new WeakSet(), _Stainless_baseURLOverridden = function _Stainless_baseURLOverridden2() { + return this.baseURL !== environments[this._options.environment || "production"]; +}; +Stainless.Stainless = _a; +Stainless.DEFAULT_TIMEOUT = 6e4; +Stainless.StainlessError = StainlessError; +Stainless.APIError = APIError; +Stainless.APIConnectionError = APIConnectionError; +Stainless.APIConnectionTimeoutError = APIConnectionTimeoutError; +Stainless.APIUserAbortError = APIUserAbortError; +Stainless.NotFoundError = NotFoundError; +Stainless.ConflictError = ConflictError; +Stainless.RateLimitError = RateLimitError; +Stainless.BadRequestError = BadRequestError; +Stainless.AuthenticationError = AuthenticationError; +Stainless.InternalServerError = InternalServerError; +Stainless.PermissionDeniedError = PermissionDeniedError; +Stainless.UnprocessableEntityError = UnprocessableEntityError; +Stainless.toFile = toFile; +Stainless.unwrapFile = unwrapFile; +Stainless.Projects = Projects; +Stainless.Builds = Builds; +Stainless.Orgs = Orgs; +Stainless.User = User; -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/lib/auth.mjs -var import_jsonwebtoken = __toESM(require_jsonwebtoken(), 1); -async function getAuthToken({ authMethods, owner, repo, logger: logger2 }) { - const method = authMethods.find((method2) => method2.owner === owner) ?? authMethods.at(-1); - if (!method || method.owner !== owner && method.owner !== "*") { - throw new Error("No matching auth method found. Did you set a fallback auth method, with owner *?"); +// src/error.ts +var ActionError = class extends Error { + constructor(message, options) { + super(message, options); + this.name = "ActionError"; } - if ("token" in method) { - return { authToken: method.token, expires: method.expires }; +}; +function maybeToActionError(error) { + if (error instanceof Stainless.BadRequestError || error instanceof Stainless.AuthenticationError || error instanceof Stainless.PermissionDeniedError || error instanceof Stainless.NotFoundError || error instanceof Stainless.UnprocessableEntityError) { + return new ActionError(error.message, { cause: error }); } - const appAuth = await getAppToken(method); - const client = createClient({ - owner, - repo, - authToken: appAuth.authToken, - resources: [BaseRepos3, BaseOrgs, BaseInstallations] - }); - let installationId = method.installationId; - try { - if (!installationId) { - if (repo) { - const { id } = await client.repos.getInstallationInfo(); - installationId = id; - } else { - const { id } = await client.orgs.retrieveInstallation(owner); - installationId = id; + return error; +} + +// src/logger.ts +var LOG_LEVELS = { + debug: 0, + info: 1, + warn: 2, + error: 3, + off: 4 +}; +var COLORS2 = { + reset: "\x1B[0m", + bold: "\x1B[1m", + dim: "\x1B[90m", + cyan: "\x1B[36m", + green: "\x1B[32m", + yellow: "\x1B[33m", + red: "\x1B[31m", + magenta: "\x1B[35m" +}; +var LEVEL_COLORS = { + debug: COLORS2.cyan, + info: COLORS2.green, + warn: COLORS2.yellow, + error: COLORS2.red +}; +var LEVEL_LABELS = { + debug: "DEBUG", + info: "INFO", + warn: "WARN", + error: "ERROR" +}; +var LABEL_WIDTH = 5; +var LOG_LEVEL_CHOICES = ["debug", "info", "warn", "error", "off"]; +function formatTimestamp() { + const now = /* @__PURE__ */ new Date(); + const pad = (n, len = 2) => n.toString().padStart(len, "0"); + return `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}.${pad(now.getMilliseconds(), 3)}`; +} +function formatArgs(args) { + if (args.length === 0) return ""; + return args.map((arg) => { + if (arg === null) return "null"; + if (arg === void 0) return "undefined"; + if (typeof arg === "string") return arg; + if (arg instanceof Error) return arg.stack || arg.message; + try { + return JSON.stringify(arg, null, 2); + } catch { + return String(arg); + } + }).join(" "); +} +function createLogFn(level, { context, minLevel, provider }) { + if (LOG_LEVELS[level] < minLevel) { + return () => { + }; + } + return (message, ...args) => { + const extra = formatArgs(args); + const line = [ + `${COLORS2.dim}${formatTimestamp()}${COLORS2.reset}`, + `${LEVEL_COLORS[level]}${COLORS2.bold}${LEVEL_LABELS[level].padEnd(LABEL_WIDTH)}${COLORS2.reset}`, + context ? `${COLORS2.magenta}[${context}]${COLORS2.reset}` : null, + message, + extra || null + ].filter(Boolean).join(" "); + const stream = level === "error" || level === "warn" ? process.stderr : process.stdout; + stream.write(line + "\n"); + if (level === "error") { + provider.emitErrorAnnotation(message + (extra ? " " + extra : "")); + } + }; +} +var BUG_REPORT_URL = "https://github.com/stainless-api/upload-openapi-spec-action/issues"; +function createLoggerImpl(logContext) { + const { provider } = logContext; + const errorFn = createLogFn("error", logContext); + const groupStack = []; + return { + debug: createLogFn("debug", logContext), + info: createLogFn("info", logContext), + warn: createLogFn("warn", logContext), + error: errorFn, + fatal(message, ...args) { + errorFn(message, ...args); + const isActionError = args.some((arg) => arg instanceof ActionError); + if (!isActionError) { + process.stderr.write( + ` +This is a bug. Please report it at ${BUG_REPORT_URL} +` + ); + } + }, + child(childContext) { + const { context, ...rest } = logContext; + const newContext = context ? `${context}:${childContext}` : childContext; + return createLoggerImpl({ context: newContext, ...rest }); + }, + group(name) { + const id = provider.startGroup(name); + groupStack.push(id); + }, + groupEnd() { + const id = groupStack.pop(); + if (id !== void 0) { + provider.endGroup(id); + } + }, + withGroup(name, fn) { + const id = provider.startGroup(name); + try { + const result = fn(); + if (result instanceof Promise) { + return result.finally(() => provider.endGroup(id)); + } + provider.endGroup(id); + return result; + } catch (e) { + provider.endGroup(id); + throw e; } } - } catch (e) { - logger2?.warn(`No installation ID found for ${owner}/${repo}, using app token instead`, e); - } - if (!installationId) { - return appAuth; - } - try { - const { token, expires_at } = await client.apps.installations.createAccessToken(installationId); - return { authToken: token, expires: new Date(expires_at) }; - } catch (e) { - logger2?.warn(`Failed to get installation token for ${installationId}, using app token instead`, e); - } - return appAuth; + }; } -async function getAppToken(method) { - const iat = Math.floor(Date.now() / 1e3) - 30; - const exp = iat + 60 * 10; - const appToken = import_jsonwebtoken.default.sign({ iat, exp, iss: method.appId }, method.privateKey, { - algorithm: "RS256" - }); - const appTokenExpires = new Date(exp * 1e3); - return { authToken: appToken, expires: appTokenExpires }; +function createLogger(options = {}) { + const minLevel = LOG_LEVELS[options.level ?? getInput("log_level", { choices: LOG_LEVEL_CHOICES }) ?? "info"]; + const provider = logging(); + return createLoggerImpl({ minLevel, provider }); } +var logger = createLogger(); -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/client.mjs -var _BaseGitHub_instances; -var _BaseGitHub_encoder; -var _BaseGitHub_baseURLOverridden; -var BaseGitHub = /* @__PURE__ */ (() => { - class BaseGitHub3 { - /** - * API Client for interfacing with the GitHub API. - * - * @param {string | null | undefined} [opts.authToken=process.env['GITHUB_AUTH_TOKEN'] ?? null] - * @param {string | null | undefined} [opts.owner] - * @param {string | null | undefined} [opts.repo] - * @param {string | null | undefined} [opts.webhookSecret=process.env['GITHUB_WEBHOOK_SECRET'] ?? null] - * @param {string} [opts.baseURL=process.env['GITHUB_BASE_URL'] ?? https://api.github.com] - Override the default base URL for the API. - * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. - * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. - * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. - * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. - * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. - * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. - */ - constructor({ baseURL = readEnv("GITHUB_BASE_URL"), authToken = readEnv("GITHUB_AUTH_TOKEN") ?? null, owner = null, repo = null, webhookSecret = readEnv("GITHUB_WEBHOOK_SECRET") ?? null, ...opts } = {}) { - _BaseGitHub_instances.add(this); - _BaseGitHub_encoder.set(this, void 0); - const options = { - authToken, - owner, - repo, - webhookSecret, - ...opts, - baseURL: baseURL || `https://api.github.com` - }; - this.baseURL = options.baseURL; - this.timeout = options.timeout ?? BaseGitHub3.DEFAULT_TIMEOUT; - this.logger = options.logger ?? console; - const defaultLogLevel = "warn"; - this.logLevel = defaultLogLevel; - this.logLevel = parseLogLevel(options.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel(readEnv("GITHUB_LOG"), "process.env['GITHUB_LOG']", this) ?? defaultLogLevel; - this.fetchOptions = options.fetchOptions; - this.maxRetries = options.maxRetries ?? 2; - this.fetch = options.fetch ?? getDefaultFetch(); - __classPrivateFieldSet(this, _BaseGitHub_encoder, FallbackEncoder, "f"); - this._options = options; - this.authToken = authToken; - this.owner = owner; - this.repo = repo; - this.webhookSecret = webhookSecret; - } - /** - * Create a new client instance re-using the same options given to the current client with optional overriding. - */ - withOptions(options) { - const client = new this.constructor({ - ...this._options, - baseURL: this.baseURL, - maxRetries: this.maxRetries, - timeout: this.timeout, - logger: this.logger, - logLevel: this.logLevel, - fetch: this.fetch, - fetchOptions: this.fetchOptions, - authToken: this.authToken, - owner: this.owner, - repo: this.repo, - webhookSecret: this.webhookSecret, - ...options - }); - return client; - } - /** - * Get Hypermedia links to resources accessible in GitHub's REST API - */ - retrieve(options) { - return this.get("/", options); - } - /** - * Get a random sentence from the Zen of GitHub - */ - zen(options) { - return this.get("/zen", { - ...options, - headers: buildHeaders([{ Accept: "text/plain" }, options?.headers]) - }); - } - defaultQuery() { - return this._options.defaultQuery; - } - validateHeaders({ values, nulls }) { - return; - } - async authHeaders(opts) { - if (this.authToken == null) { - return void 0; - } - return buildHeaders([{ Authorization: `Bearer ${this.authToken}` }]); - } - /** - * Given a list of available auth methods, get an auth token to access the - * given GitHub `owner` (and optionally `repo`), and set it on this client. - */ - async getAuthToken(opts) { - if (this.authToken != null) { - return this.authToken; - } - const owner = opts.owner ?? this.owner; - const repo = opts.repo ?? this.repo; - if (owner == null) { - throw new Error("Specify an owner to get a token for."); +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/errors.mjs +function isAbortError2(err) { + return typeof err === "object" && err !== null && // Spec-compliant fetch implementations + ("name" in err && err.name === "AbortError" || // Expo fetch + "message" in err && String(err.message).includes("FetchRequestCanceledException")); +} +var castToError2 = (err) => { + if (err instanceof Error) + return err; + if (typeof err === "object" && err !== null) { + try { + if (Object.prototype.toString.call(err) === "[object Error]") { + const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); + if (err.stack) + error.stack = err.stack; + if (err.cause && !error.cause) + error.cause = err.cause; + if (err.name) + error.name = err.name; + return error; } - const { authToken } = await getAuthToken({ - authMethods: opts.authMethods, - owner, - repo, - logger: this.logger - }); - this.authToken = authToken; - return authToken; + } catch { } - stringifyQuery(query) { - return stringify(query, { arrayFormat: "comma" }); + try { + return new Error(JSON.stringify(err)); + } catch { } - getUserAgent() { - return `${this.constructor.name}/JS ${VERSION}`; + } + return new Error(err); +}; + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/core/error.mjs +var GitHubError = /* @__PURE__ */ (() => { + class GitHubError2 extends Error { + } + return GitHubError2; +})(); +var APIError2 = class _APIError extends GitHubError { + constructor(status, error, message, headers) { + super(`${_APIError.makeMessage(status, error, message)}`); + this.status = status; + this.headers = headers; + this.error = error; + } + static makeMessage(status, error, message) { + const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message; + if (status && msg) { + return `${status} ${msg}`; } - defaultIdempotencyKey() { - return `stainless-node-retry-${uuid4()}`; + if (status) { + return `${status} status code (no body)`; } - makeStatusError(status, error, message, headers) { - return APIError.generate(status, error, message, headers); + if (msg) { + return msg; } - buildURL(path7, query, defaultBaseURL) { - const baseURL = !__classPrivateFieldGet(this, _BaseGitHub_instances, "m", _BaseGitHub_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL; - const url = isAbsoluteURL(path7) ? new URL(path7) : new URL(baseURL + (baseURL.endsWith("/") && path7.startsWith("/") ? path7.slice(1) : path7)); - const defaultQuery = this.defaultQuery(); - if (!isEmptyObj(defaultQuery)) { - query = { ...defaultQuery, ...query }; - } - if (typeof query === "object" && query && !Array.isArray(query)) { - url.search = this.stringifyQuery(query); - } - return url.toString(); + return "(no status code or body)"; + } + static generate(status, errorResponse, message, headers) { + if (!status || !headers) { + return new APIConnectionError2({ message, cause: castToError2(errorResponse) }); } - /** - * Used as a callback for mutating the given `FinalRequestOptions` object. - */ - async prepareOptions(options) { + const error = errorResponse; + if (status === 400) { + return new BadRequestError2(status, error, message, headers); } - /** - * Used as a callback for mutating the given `RequestInit` object. - * - * This is useful for cases where you want to add certain headers based off of - * the request properties, e.g. `method` or `url`. - */ - async prepareRequest(request, { url, options }) { + if (status === 401) { + return new AuthenticationError2(status, error, message, headers); } - get(path7, opts) { - return this.methodRequest("get", path7, opts); + if (status === 403) { + return new PermissionDeniedError2(status, error, message, headers); } - post(path7, opts) { - return this.methodRequest("post", path7, opts); + if (status === 404) { + return new NotFoundError2(status, error, message, headers); } - patch(path7, opts) { - return this.methodRequest("patch", path7, opts); + if (status === 409) { + return new ConflictError2(status, error, message, headers); } - put(path7, opts) { - return this.methodRequest("put", path7, opts); + if (status === 422) { + return new UnprocessableEntityError2(status, error, message, headers); } - delete(path7, opts) { - return this.methodRequest("delete", path7, opts); + if (status === 429) { + return new RateLimitError2(status, error, message, headers); } - methodRequest(method, path7, opts) { - return this.request(Promise.resolve(opts).then((opts2) => { - return { method, path: path7, ...opts2 }; - })); + if (status >= 500) { + return new InternalServerError2(status, error, message, headers); } - request(options, remainingRetries = null) { - return new APIPromise(this, this.makeRequest(options, remainingRetries, void 0)); + return new _APIError(status, error, message, headers); + } +}; +var APIUserAbortError2 = class extends APIError2 { + constructor({ message } = {}) { + super(void 0, void 0, message || "Request was aborted.", void 0); + } +}; +var APIConnectionError2 = class extends APIError2 { + constructor({ message, cause }) { + super(void 0, void 0, message || "Connection error.", void 0); + if (cause) + this.cause = cause; + } +}; +var APIConnectionTimeoutError2 = class extends APIConnectionError2 { + constructor({ message } = {}) { + super({ message: message ?? "Request timed out." }); + } +}; +var BadRequestError2 = class extends APIError2 { +}; +var AuthenticationError2 = class extends APIError2 { +}; +var PermissionDeniedError2 = class extends APIError2 { +}; +var NotFoundError2 = class extends APIError2 { +}; +var ConflictError2 = class extends APIError2 { +}; +var UnprocessableEntityError2 = class extends APIError2 { +}; +var RateLimitError2 = class extends APIError2 { +}; +var InternalServerError2 = class extends APIError2 { +}; + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/core/resource.mjs +var APIResource2 = /* @__PURE__ */ (() => { + class APIResource4 { + constructor(client) { + this._client = client; } - async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { - const options = await optionsInput; - const maxRetries = options.maxRetries ?? this.maxRetries; - if (retriesRemaining == null) { - retriesRemaining = maxRetries; - } - await this.prepareOptions(options); - const { req, url, timeout } = await this.buildRequest(options, { - retryCount: maxRetries - retriesRemaining - }); - await this.prepareRequest(req, { url, options }); - const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0"); - const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`; - const startTime = Date.now(); - loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({ - retryOfRequestLogID, - method: options.method, - url, - options, - headers: req.headers - })); - if (options.signal?.aborted) { - throw new APIUserAbortError(); - } - const controller = new AbortController(); - const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError); - const headersTime = Date.now(); - if (response instanceof globalThis.Error) { - const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; - if (options.signal?.aborted) { - throw new APIUserAbortError(); - } - const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : "")); - if (retriesRemaining) { - loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`); - loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails({ - retryOfRequestLogID, - url, - durationMs: headersTime - startTime, - message: response.message - })); - return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); - } - loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`); - loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails({ - retryOfRequestLogID, - url, - durationMs: headersTime - startTime, - message: response.message - })); - if (isTimeout) { - throw new APIConnectionTimeoutError(); - } - throw new APIConnectionError({ cause: response }); - } - const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`; - if (!response.ok) { - const shouldRetry = await this.shouldRetry(response); - if (retriesRemaining && shouldRetry) { - const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`; - await CancelReadableStream(response.body); - loggerFor(this).info(`${responseInfo} - ${retryMessage2}`); - loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - durationMs: headersTime - startTime - })); - return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); - } - const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; - loggerFor(this).info(`${responseInfo} - ${retryMessage}`); - const errText = await response.text().catch((err2) => castToError(err2).message); - const errJSON = safeJSON(errText); - const errMessage = errJSON ? void 0 : errText; - loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - message: errMessage, - durationMs: Date.now() - startTime - })); - const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); - throw err; - } - loggerFor(this).info(responseInfo); - loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - durationMs: headersTime - startTime - })); - return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; + } + APIResource4._key = []; + return APIResource4; +})(); + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/tslib.mjs +function __classPrivateFieldSet2(receiver, state, value, kind, f) { + if (kind === "m") + throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; +} +function __classPrivateFieldGet2(receiver, state, kind, f) { + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/utils/values.mjs +var startsWithSchemeRegexp2 = /^[a-z][a-z0-9+.-]*:/i; +var isAbsoluteURL2 = (url) => { + return startsWithSchemeRegexp2.test(url); +}; +var isArray2 = (val) => (isArray2 = Array.isArray, isArray2(val)); +var isReadonlyArray2 = isArray2; +function maybeObj2(x) { + if (typeof x !== "object") { + return {}; + } + return x ?? {}; +} +function isEmptyObj2(obj) { + if (!obj) + return true; + for (const _k in obj) + return false; + return true; +} +function hasOwn2(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +var validatePositiveInteger2 = (name, n) => { + if (typeof n !== "number" || !Number.isInteger(n)) { + throw new GitHubError(`${name} must be an integer`); + } + if (n < 0) { + throw new GitHubError(`${name} must be a positive integer`); + } + return n; +}; +var safeJSON2 = (text) => { + try { + return JSON.parse(text); + } catch (err) { + return void 0; + } +}; + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/utils/log.mjs +var levelNumbers2 = { + off: 0, + error: 200, + warn: 300, + info: 400, + debug: 500 +}; +var parseLogLevel2 = (maybeLevel, sourceName, client) => { + if (!maybeLevel) { + return void 0; + } + if (hasOwn2(levelNumbers2, maybeLevel)) { + return maybeLevel; + } + loggerFor2(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers2))}`); + return void 0; +}; +function noop2() { +} +function makeLogFn2(fnLevel, logger2, logLevel) { + if (!logger2 || levelNumbers2[fnLevel] > levelNumbers2[logLevel]) { + return noop2; + } else { + return logger2[fnLevel].bind(logger2); + } +} +var noopLogger2 = { + error: noop2, + warn: noop2, + info: noop2, + debug: noop2 +}; +var cachedLoggers2 = /* @__PURE__ */ new WeakMap(); +function loggerFor2(client) { + const logger2 = client.logger; + const logLevel = client.logLevel ?? "off"; + if (!logger2) { + return noopLogger2; + } + const cachedLogger = cachedLoggers2.get(logger2); + if (cachedLogger && cachedLogger[0] === logLevel) { + return cachedLogger[1]; + } + const levelLogger = { + error: makeLogFn2("error", logger2, logLevel), + warn: makeLogFn2("warn", logger2, logLevel), + info: makeLogFn2("info", logger2, logLevel), + debug: makeLogFn2("debug", logger2, logLevel) + }; + cachedLoggers2.set(logger2, [logLevel, levelLogger]); + return levelLogger; +} +var formatRequestDetails2 = (details) => { + if (details.options) { + details.options = { ...details.options }; + delete details.options["headers"]; + } + if (details.headers) { + details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ + name, + name.toLowerCase() === "authorization" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value + ])); + } + if ("retryOfRequestLogID" in details) { + if (details.retryOfRequestLogID) { + details.retryOf = details.retryOfRequestLogID; } - getAPIList(path7, Page2, opts) { - return this.requestAPIList(Page2, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path7, ...opts2 })) : { method: "get", path: path7, ...opts }); + delete details.retryOfRequestLogID; + } + return details; +}; + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/parse.mjs +async function defaultParseResponse2(client, props) { + const { response, requestLogID, retryOfRequestLogID, startTime } = props; + const body = await (async () => { + if (response.status === 204) { + return null; } - requestAPIList(Page2, options) { - const request = this.makeRequest(options, null, void 0); - return new PagePromise(this, request, Page2); + if (props.options.__binaryResponse) { + return response; } - async fetchWithTimeout(url, init, ms, controller) { - const { signal, method, ...options } = init || {}; - const abort = this._makeAbort(controller); - if (signal) - signal.addEventListener("abort", abort, { once: true }); - const timeout = setTimeout(abort, ms); - const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body; - const fetchOptions = { - signal: controller.signal, - ...isReadableBody ? { duplex: "half" } : {}, - method: "GET", - ...options - }; - if (method) { - fetchOptions.method = method.toUpperCase(); - } - try { - return await this.fetch.call(void 0, url, fetchOptions); - } finally { - clearTimeout(timeout); + const contentType = response.headers.get("content-type"); + const mediaType = contentType?.split(";")[0]?.trim(); + const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json"); + if (isJSON) { + const contentLength = response.headers.get("content-length"); + if (contentLength === "0") { + return void 0; } + const json = await response.json(); + return json; } - async shouldRetry(response) { - const shouldRetryHeader = response.headers.get("x-should-retry"); - if (shouldRetryHeader === "true") - return true; - if (shouldRetryHeader === "false") - return false; - if (response.status === 408) - return true; - if (response.status === 409) - return true; - if (response.status === 429) - return true; - if (response.status >= 500) - return true; - return false; + const text = await response.text(); + return text; + })(); + loggerFor2(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails2({ + retryOfRequestLogID, + url: response.url, + status: response.status, + body, + durationMs: Date.now() - startTime + })); + return body; +} + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/core/api-promise.mjs +var _APIPromise_client2; +var APIPromise2 = /* @__PURE__ */ (() => { + class APIPromise4 extends Promise { + constructor(client, responsePromise, parseResponse = defaultParseResponse2) { + super((resolve) => { + resolve(null); + }); + this.responsePromise = responsePromise; + this.parseResponse = parseResponse; + _APIPromise_client2.set(this, void 0); + __classPrivateFieldSet2(this, _APIPromise_client2, client, "f"); } - async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { - let timeoutMillis; - const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms"); - if (retryAfterMillisHeader) { - const timeoutMs = parseFloat(retryAfterMillisHeader); - if (!Number.isNaN(timeoutMs)) { - timeoutMillis = timeoutMs; - } - } - const retryAfterHeader = responseHeaders?.get("retry-after"); - if (retryAfterHeader && !timeoutMillis) { - const timeoutSeconds = parseFloat(retryAfterHeader); - if (!Number.isNaN(timeoutSeconds)) { - timeoutMillis = timeoutSeconds * 1e3; - } else { - timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); - } - } - if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1e3)) { - const maxRetries = options.maxRetries ?? this.maxRetries; - timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); - } - await sleep(timeoutMillis); - return this.makeRequest(options, retriesRemaining - 1, requestLogID); + _thenUnwrap(transform) { + return new APIPromise4(__classPrivateFieldGet2(this, _APIPromise_client2, "f"), this.responsePromise, async (client, props) => transform(await this.parseResponse(client, props), props)); } - calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { - const initialRetryDelay = 0.5; - const maxRetryDelay = 8; - const numRetries = maxRetries - retriesRemaining; - const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); - const jitter = 1 - Math.random() * 0.25; - return sleepSeconds * jitter * 1e3; + /** + * Gets the raw `Response` instance instead of parsing the response + * data. + * + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + asResponse() { + return this.responsePromise.then((p) => p.response); } - async buildRequest(inputOptions, { retryCount = 0 } = {}) { - const options = { ...inputOptions }; - const { method, path: path7, query, defaultBaseURL } = options; - const url = this.buildURL(path7, query, defaultBaseURL); - if ("timeout" in options) - validatePositiveInteger("timeout", options.timeout); - options.timeout = options.timeout ?? this.timeout; - const { bodyHeaders, body } = this.buildBody({ options }); - const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); - const req = { - method, - headers: reqHeaders, - ...options.signal && { signal: options.signal }, - ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" }, - ...body && { body }, - ...this.fetchOptions ?? {}, - ...options.fetchOptions ?? {} - }; - return { req, url, timeout: options.timeout }; + /** + * Gets the parsed response data and the raw `Response` instance. + * + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + async withResponse() { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { data, response }; } - async buildHeaders({ options, method, bodyHeaders, retryCount }) { - let idempotencyHeaders = {}; - if (this.idempotencyHeader && method !== "get") { - if (!options.idempotencyKey) - options.idempotencyKey = this.defaultIdempotencyKey(); - idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; + parse() { + if (!this.parsedPromise) { + this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet2(this, _APIPromise_client2, "f"), data)); } - const headers = buildHeaders([ - idempotencyHeaders, - { - Accept: "application/json", - "User-Agent": this.getUserAgent(), - "X-Stainless-Retry-Count": String(retryCount), - ...options.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options.timeout / 1e3)) } : {}, - ...getPlatformHeaders() - }, - await this.authHeaders(options), - this._options.defaultHeaders, - bodyHeaders, - options.headers - ]); - this.validateHeaders(headers); - return headers.values; + return this.parsedPromise; } - _makeAbort(controller) { - return () => controller.abort(); + then(onfulfilled, onrejected) { + return this.parse().then(onfulfilled, onrejected); } - buildBody({ options: { body, headers: rawHeaders } }) { - if (!body) { - return { bodyHeaders: void 0, body: void 0 }; - } - const headers = buildHeaders([rawHeaders]); - if ( - // Pass raw type verbatim - ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && // Preserve legacy string encoding behavior for now - headers.values.has("content-type") || // `Blob` is superset of `File` - globalThis.Blob && body instanceof globalThis.Blob || // `FormData` -> `multipart/form-data` - body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded` - body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`) - globalThis.ReadableStream && body instanceof globalThis.ReadableStream - ) { - return { bodyHeaders: void 0, body }; - } else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) { - return { bodyHeaders: void 0, body: ReadableStreamFrom(body) }; - } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") { - return { - bodyHeaders: { "content-type": "application/x-www-form-urlencoded" }, - body: this.stringifyQuery(body) - }; - } else { - return __classPrivateFieldGet(this, _BaseGitHub_encoder, "f").call(this, { body, headers }); - } + catch(onrejected) { + return this.parse().catch(onrejected); + } + finally(onfinally) { + return this.parse().finally(onfinally); } } - _BaseGitHub_encoder = /* @__PURE__ */ new WeakMap(), _BaseGitHub_instances = /* @__PURE__ */ new WeakSet(), _BaseGitHub_baseURLOverridden = function _BaseGitHub_baseURLOverridden2() { - return this.baseURL !== "https://api.github.com"; - }; - BaseGitHub3.DEFAULT_TIMEOUT = 6e4; - return BaseGitHub3; + _APIPromise_client2 = /* @__PURE__ */ new WeakMap(); + return APIPromise4; })(); -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/tree-shakable.mjs -function createClient(options) { - const client = new BaseGitHub(options); - for (const ResourceClass of options.resources) { - const resourceInstance = new ResourceClass(client); - let object = client; - for (const part of ResourceClass._key.slice(0, -1)) { - if (hasOwn(object, part)) { - object = object[part]; - } else { - Object.defineProperty(object, part, { - value: object = {}, - configurable: true, - enumerable: true, - writable: true - }); +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/core/pagination.mjs +var _AbstractPage_client2; +var AbstractPage2 = /* @__PURE__ */ (() => { + class AbstractPage3 { + constructor(client, response, body, options) { + _AbstractPage_client2.set(this, void 0); + __classPrivateFieldSet2(this, _AbstractPage_client2, client, "f"); + this.options = options; + this.response = response; + this.body = body; + } + hasNextPage() { + const items = this.getPaginatedItems(); + if (!items.length) + return false; + return this.nextPageRequestOptions() != null; + } + async getNextPage() { + const nextOptions = this.nextPageRequestOptions(); + if (!nextOptions) { + throw new GitHubError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`."); } + return await __classPrivateFieldGet2(this, _AbstractPage_client2, "f").requestAPIList(this.constructor, nextOptions); } - const name = ResourceClass._key.at(-1); - if (!hasOwn(object, name)) { - Object.defineProperty(object, name, { - value: resourceInstance, - configurable: true, - enumerable: true, - writable: true - }); - } else { - if (object[name] instanceof APIResource) { - throw new TypeError(`Resource at ${ResourceClass._key.join(".")} already exists!`); - } else { - object[name] = Object.assign(resourceInstance, object[name]); + async *iterPages() { + let page = this; + yield page; + while (page.hasNextPage()) { + page = await page.getNextPage(); + yield page; + } + } + async *[(_AbstractPage_client2 = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() { + for await (const page of this.iterPages()) { + for (const item of page.getPaginatedItems()) { + yield item; + } } } } - return client; -} - -// src/compat/github/context.ts -var fs = __toESM(require("node:fs")); -var cachedContext; -function getGitHubContext() { - if (cachedContext) { - return cachedContext; - } - const [owner, repo] = process.env.GITHUB_REPOSITORY?.split("/") ?? []; - const runID = process.env.GITHUB_RUN_ID; - if (!owner || !repo || !runID) { - throw new Error( - "Expected env vars GITHUB_REPOSITORY and GITHUB_RUN_ID to be set." - ); - } - const host = process.env.GITHUB_SERVER_URL || "https://github.com"; - const apiURL = process.env.GITHUB_API_URL || "https://api.github.com"; - const runURL = `${host}/${owner}/${repo}/actions/runs/${runID}`; - let defaultBranch = null; - let prNumber = null; - try { - const eventPath = process.env.GITHUB_EVENT_PATH; - const payload = eventPath && fs.existsSync(eventPath) && JSON.parse(fs.readFileSync(eventPath, "utf-8")); - const maybeDefaultBranch = payload?.repository?.default_branch; - if (typeof maybeDefaultBranch === "string") { - defaultBranch = maybeDefaultBranch; + return AbstractPage3; +})(); +var PagePromise2 = /* @__PURE__ */ (() => { + class PagePromise3 extends APIPromise2 { + constructor(client, request, Page2) { + super(client, request, async (client2, props) => new Page2(client2, props.response, await defaultParseResponse2(client2, props), props.options)); } - const maybePRNumber = parseInt( - payload?.pull_request?.number ?? process.env.PR_NUMBER ?? "", - 10 - ); - if (Number.isInteger(maybePRNumber)) { - prNumber = maybePRNumber; + /** + * Allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ + async *[Symbol.asyncIterator]() { + const page = await this; + for await (const item of page) { + yield item; + } } - } catch (e) { - throw new Error(`Failed to parse GitHub event: ${e}`); - } - const refName = process.env.GITHUB_REF_NAME || null; - const sha = process.env.GITHUB_SHA || null; - cachedContext = { - provider: "github", - host, - owner, - repo, - urls: { api: apiURL, run: runURL }, - names: { ci: "GitHub Actions", pr: "PR", provider: "GitHub" }, - defaultBranch, - prNumber, - refName, - sha - }; - logger.debug("GitHub context", cachedContext); - return cachedContext; -} - -// src/compat/github/api.ts -var GitHubClient = class { - client; - constructor(token) { - this.client = createClient({ - authToken: token, - baseURL: getGitHubContext().urls.api, - owner: getGitHubContext().owner, - repo: getGitHubContext().repo, - resources: [BaseCommits, BaseComments2, BasePulls], - logLevel: "warn", - logger - }); - } - async listComments(prNumber) { - const { data } = await this.client.repos.issues.comments.list(prNumber); - return data.map((c) => ({ id: c.id, body: c.body ?? "" })); } - async createComment(prNumber, props) { - const data = await this.client.repos.issues.comments.create( - prNumber, - props - ); - return { id: data.id, body: data.body }; + return PagePromise3; +})(); +var NumberedPage = class extends AbstractPage2 { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body || []; } - async updateComment(_prNumber, { id, body }) { - const data = await this.client.repos.issues.comments.update(id, { - body - }); - return { id: data.id, body: data.body }; + getPaginatedItems() { + return this.data ?? []; } - async getPullRequest(number) { - const data = await this.client.repos.pulls.retrieve(number); + nextPageRequestOptions() { + const query = this.options.query; + const currentPage = query?.page ?? 1; return { - number, - state: data.merged_at ? "merged" : data.state, - title: data.title, - base_sha: data.base.sha, - base_ref: data.base.ref, - head_ref: data.head.ref, - head_sha: data.head.sha, - merge_commit_sha: data.merge_commit_sha - }; - } - async getPullRequestForCommit(sha) { - const pullRequests = await this.client.repos.commits.listPullRequests(sha).then( - ({ data }) => data.filter((c) => c.merged_at || c.state !== "closed") - ).catch((err) => { - if (err instanceof APIError && (err.status === 401 || err.status === 403 || err.status === 404)) { - return []; + ...this.options, + query: { + ...maybeObj2(this.options.query), + page: currentPage + 1 } - throw err; - }); - if (pullRequests.length === 0) { - return null; - } - if (pullRequests.length > 1) { - logger.warn( - `Multiple pull requests found for commit; only using first.`, - { commit: sha, pulls: pullRequests.map((c) => c.number) } - ); - } - const pull = pullRequests[0]; - return { - number: pull.number, - state: pull.merged_at ? "merged" : pull.state, - title: pull.title, - base_sha: pull.base.sha, - base_ref: pull.base.ref, - head_ref: pull.head.ref, - head_sha: pull.head.sha, - merge_commit_sha: pull.merge_commit_sha }; } }; -var cachedClient; -function getGitHubClient() { - if (cachedClient !== void 0) { - return cachedClient; - } - const token = getInput("github_token"); - if (token) { - cachedClient = new GitHubClient(token); - } else { - logger.info("No GitHub token found via input 'github_token'."); - cachedClient = null; - } - return cachedClient; -} -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/errors.mjs -function isAbortError2(err) { - return typeof err === "object" && err !== null && // Spec-compliant fetch implementations - ("name" in err && err.name === "AbortError" || // Expo fetch - "message" in err && String(err.message).includes("FetchRequestCanceledException")); +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/utils/path.mjs +function encodeURIPath2(str) { + return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); } -var castToError2 = (err) => { - if (err instanceof Error) - return err; - if (typeof err === "object" && err !== null) { - try { - if (Object.prototype.toString.call(err) === "[object Error]") { - const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); - if (err.stack) - error.stack = err.stack; - if (err.cause && !error.cause) - error.cause = err.cause; - if (err.name) - error.name = err.name; - return error; - } - } catch { +var EMPTY2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); +var createPathTagFunction2 = (pathEncoder = encodeURIPath2) => function path7(statics, ...params) { + if (statics.length === 1) + return statics[0]; + let postPath = false; + const invalidSegments = []; + const path8 = statics.reduce((previousValue, currentValue, index) => { + if (/[?#]/.test(currentValue)) { + postPath = true; } - try { - return new Error(JSON.stringify(err)); - } catch { + const value = params[index]; + let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value); + if (index !== params.length && (value == null || typeof value === "object" && // handle values from other realms + value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY2) ?? EMPTY2)?.toString)) { + encoded = value + ""; + invalidSegments.push({ + start: previousValue.length + currentValue.length, + length: encoded.length, + error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter` + }); } + return previousValue + currentValue + (index === params.length ? "" : encoded); + }, ""); + const pathOnly = path8.split(/[?#]/, 1)[0]; + const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; + let match; + while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) { + invalidSegments.push({ + start: match.index, + length: match[0].length, + error: `Value "${match[0]}" can't be safely passed as a path parameter` + }); + } + invalidSegments.sort((a, b) => a.start - b.start); + if (invalidSegments.length > 0) { + let lastEnd = 0; + const underline = invalidSegments.reduce((acc, segment) => { + const spaces = " ".repeat(segment.start - lastEnd); + const arrows = "^".repeat(segment.length); + lastEnd = segment.start + segment.length; + return acc + spaces + arrows; + }, ""); + throw new GitHubError(`Path parameters result in path with invalid segments: +${invalidSegments.map((e) => e.error).join("\n")} +${path8} +${underline}`); } - return new Error(err); + return path8; }; +var path2 = /* @__PURE__ */ createPathTagFunction2(encodeURIPath2); -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/core/error.mjs -var GitLabError = /* @__PURE__ */ (() => { - class GitLabError2 extends Error { - } - return GitLabError2; -})(); -var APIError2 = class _APIError extends GitLabError { - constructor(status, error, message, headers) { - super(`${_APIError.makeMessage(status, error, message)}`); - this.status = status; - this.headers = headers; - this.error = error; - } - static makeMessage(status, error, message) { - const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message; - if (status && msg) { - return `${status} ${msg}`; - } - if (status) { - return `${status} status code (no body)`; - } - if (msg) { - return msg; - } - return "(no status code or body)"; - } - static generate(status, errorResponse, message, headers) { - if (!status || !headers) { - return new APIConnectionError2({ message, cause: castToError2(errorResponse) }); - } - const error = errorResponse; - if (status === 400) { - return new BadRequestError2(status, error, message, headers); - } - if (status === 401) { - return new AuthenticationError2(status, error, message, headers); +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/resources/repos/commits/commits.mjs +var BaseCommits = /* @__PURE__ */ (() => { + class BaseCommits4 extends APIResource2 { + /** + * Returns the contents of a single commit reference. You must have `read` access + * for the repository to use this endpoint. + * + * > [!NOTE] If there are more than 300 files in the commit diff and the default + * > JSON media type is requested, the response will include pagination link + * > headers for the remaining files, up to a limit of 3000 files. Each page + * > contains the static commit information, and the only changes are to the file + * > listing. + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * Pagination query parameters are not supported for these media types. + * + * - **`application/vnd.github.diff`**: Returns the diff of the commit. Larger + * diffs may time out and return a 5xx status code. + * - **`application/vnd.github.patch`**: Returns the patch of the commit. Diffs + * with binary data will have no `patch` property. Larger diffs may time out and + * return a 5xx status code. + * - **`application/vnd.github.sha`**: Returns the commit's SHA-1 hash. You can use + * this endpoint to check if a remote reference's SHA-1 hash is the same as your + * local reference's SHA-1 hash by providing the local SHA-1 reference as the + * ETag. + * + * **Signature verification object** + * + * The response will include a `verification` object that describes the result of + * verifying the commit's signature. The following fields are included in the + * `verification` object: + * + * | Name | Type | Description | + * | ------------- | --------- | ------------------------------------------------------------------------------------------------ | + * | `verified` | `boolean` | Indicates whether GitHub considers the signature in this commit to be verified. | + * | `reason` | `string` | The reason for verified value. Possible values and their meanings are enumerated in table below. | + * | `signature` | `string` | The signature that was extracted from the commit. | + * | `payload` | `string` | The value that was signed. | + * | `verified_at` | `string` | The date the signature was verified by GitHub. | + * + * These are the possible values for `reason` in the `verification` object: + * + * | Value | Description | + * | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------- | + * | `expired_key` | The key that made the signature is expired. | + * | `not_signing_key` | The "signing" flag is not among the usage flags in the GPG key that made the signature. | + * | `gpgverify_error` | There was an error communicating with the signature verification service. | + * | `gpgverify_unavailable` | The signature verification service is currently unavailable. | + * | `unsigned` | The object does not include a signature. | + * | `unknown_signature_type` | A non-PGP signature was found in the commit. | + * | `no_user` | No user was associated with the `committer` email address in the commit. | + * | `unverified_email` | The `committer` email address in the commit was associated with a user, but the email address is not verified on their account. | + * | `bad_email` | The `committer` email address in the commit is not included in the identities of the PGP key that made the signature. | + * | `unknown_key` | The key that made the signature has not been registered with any user's account. | + * | `malformed_signature` | There was an error parsing the signature. | + * | `invalid` | The signature could not be cryptographically verified using the key whose key-id was found in the signature. | + * | `valid` | None of the above errors applied, so the signature is considered to be verified. | + * + * @example + * ```ts + * const commit = await client.repos.commits.retrieve('ref', { + * owner: 'owner', + * repo: 'repo', + * }); + * ``` + */ + retrieve(ref, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/commits/${ref}`, { query, ...options }); } - if (status === 403) { - return new PermissionDeniedError2(status, error, message, headers); + /** + * **Signature verification object** + * + * The response will include a `verification` object that describes the result of + * verifying the commit's signature. The following fields are included in the + * `verification` object: + * + * | Name | Type | Description | + * | ------------- | --------- | ------------------------------------------------------------------------------------------------ | + * | `verified` | `boolean` | Indicates whether GitHub considers the signature in this commit to be verified. | + * | `reason` | `string` | The reason for verified value. Possible values and their meanings are enumerated in table below. | + * | `signature` | `string` | The signature that was extracted from the commit. | + * | `payload` | `string` | The value that was signed. | + * | `verified_at` | `string` | The date the signature was verified by GitHub. | + * + * These are the possible values for `reason` in the `verification` object: + * + * | Value | Description | + * | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------- | + * | `expired_key` | The key that made the signature is expired. | + * | `not_signing_key` | The "signing" flag is not among the usage flags in the GPG key that made the signature. | + * | `gpgverify_error` | There was an error communicating with the signature verification service. | + * | `gpgverify_unavailable` | The signature verification service is currently unavailable. | + * | `unsigned` | The object does not include a signature. | + * | `unknown_signature_type` | A non-PGP signature was found in the commit. | + * | `no_user` | No user was associated with the `committer` email address in the commit. | + * | `unverified_email` | The `committer` email address in the commit was associated with a user, but the email address is not verified on their account. | + * | `bad_email` | The `committer` email address in the commit is not included in the identities of the PGP key that made the signature. | + * | `unknown_key` | The key that made the signature has not been registered with any user's account. | + * | `malformed_signature` | There was an error parsing the signature. | + * | `invalid` | The signature could not be cryptographically verified using the key whose key-id was found in the signature. | + * | `valid` | None of the above errors applied, so the signature is considered to be verified. | + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const commit of client.repos.commits.list({ + * owner: 'owner', + * repo: 'repo', + * })) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.getAPIList(path2`/repos/${owner}/${repo}/commits`, NumberedPage, { + query, + ...options + }); } - if (status === 404) { - return new NotFoundError2(status, error, message, headers); + /** + * Protected branches are available in public repositories with GitHub Free and + * GitHub Free for organizations, and in public and private repositories with + * GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. + * For more information, see + * [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) + * in the GitHub Help documentation. + * + * Returns all branches where the given commit SHA is the HEAD, or latest commit + * for the branch. + * + * @example + * ```ts + * const response = + * await client.repos.commits.listBranchesWhereHead( + * 'commit_sha', + * { owner: 'owner', repo: 'repo' }, + * ); + * ``` + */ + listBranchesWhereHead(commitSha, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/commits/${commitSha}/branches-where-head`, options); } - if (status === 409) { - return new ConflictError2(status, error, message, headers); + /** + * Lists check runs for a commit ref. The `ref` can be a SHA, branch name, or a tag + * name. + * + * > [!NOTE] The endpoints to manage checks only look for pushes in the repository + * > where the check suite or check run were created. Pushes to a branch in a + * > forked repository are not detected and return an empty `pull_requests` array. + * + * If there are more than 1000 check suites on a single git reference, this + * endpoint will limit check runs to the 1000 most recent check suites. To iterate + * over all possible check runs, use the + * [List check suites for a Git reference](https://docs.github.com/rest/reference/checks#list-check-suites-for-a-git-reference) + * endpoint and provide the `check_suite_id` parameter to the + * [List check runs in a check suite](https://docs.github.com/rest/reference/checks#list-check-runs-in-a-check-suite) + * endpoint. + * + * OAuth app tokens and personal access tokens (classic) need the `repo` scope to + * use this endpoint on a private repository. + * + * @example + * ```ts + * const response = await client.repos.commits.listCheckRuns( + * 'ref', + * { owner: 'owner', repo: 'repo' }, + * ); + * ``` + */ + listCheckRuns(ref, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/commits/${ref}/check-runs`, { query, ...options }); } - if (status === 422) { - return new UnprocessableEntityError2(status, error, message, headers); + /** + * Lists check suites for a commit `ref`. The `ref` can be a SHA, branch name, or a + * tag name. + * + * > [!NOTE] The endpoints to manage checks only look for pushes in the repository + * > where the check suite or check run were created. Pushes to a branch in a + * > forked repository are not detected and return an empty `pull_requests` array + * > and a `null` value for `head_branch`. + * + * OAuth app tokens and personal access tokens (classic) need the `repo` scope to + * use this endpoint on a private repository. + * + * @example + * ```ts + * const response = await client.repos.commits.listCheckSuites( + * 'ref', + * { owner: 'owner', repo: 'repo' }, + * ); + * ``` + */ + listCheckSuites(ref, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/commits/${ref}/check-suites`, { query, ...options }); } - if (status === 429) { - return new RateLimitError2(status, error, message, headers); + /** + * Lists the merged pull request that introduced the commit to the repository. If + * the commit is not present in the default branch, it will return merged and open + * pull requests associated with the commit. + * + * To list the open or merged pull requests associated with a branch, you can set + * the `commit_sha` parameter to the branch name. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const pullRequestSimple of client.repos.commits.listPullRequests( + * 'commit_sha', + * { owner: 'owner', repo: 'repo' }, + * )) { + * // ... + * } + * ``` + */ + listPullRequests(commitSha, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.getAPIList(path2`/repos/${owner}/${repo}/commits/${commitSha}/pulls`, NumberedPage, { query, ...options }); } - if (status >= 500) { - return new InternalServerError2(status, error, message, headers); + /** + * Users with pull access in a repository can view commit statuses for a given ref. + * The ref can be a SHA, a branch name, or a tag name. Statuses are returned in + * reverse chronological order. The first status in the list will be the latest + * one. + * + * This resource is also available via a legacy route: + * `GET /repos/:owner/:repo/statuses/:ref`. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const commitListStatusesResponse of client.repos.commits.listStatuses( + * 'ref', + * { owner: 'owner', repo: 'repo' }, + * )) { + * // ... + * } + * ``` + */ + listStatuses(ref, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.getAPIList(path2`/repos/${owner}/${repo}/commits/${ref}/statuses`, NumberedPage, { query, ...options }); } - return new _APIError(status, error, message, headers); - } -}; -var APIUserAbortError2 = class extends APIError2 { - constructor({ message } = {}) { - super(void 0, void 0, message || "Request was aborted.", void 0); - } -}; -var APIConnectionError2 = class extends APIError2 { - constructor({ message, cause }) { - super(void 0, void 0, message || "Connection error.", void 0); - if (cause) - this.cause = cause; - } -}; -var APIConnectionTimeoutError2 = class extends APIConnectionError2 { - constructor({ message } = {}) { - super({ message: message ?? "Request timed out." }); - } -}; -var BadRequestError2 = class extends APIError2 { -}; -var AuthenticationError2 = class extends APIError2 { -}; -var PermissionDeniedError2 = class extends APIError2 { -}; -var NotFoundError2 = class extends APIError2 { -}; -var ConflictError2 = class extends APIError2 { -}; -var UnprocessableEntityError2 = class extends APIError2 { -}; -var RateLimitError2 = class extends APIError2 { -}; -var InternalServerError2 = class extends APIError2 { -}; - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/core/resource.mjs -var APIResource2 = /* @__PURE__ */ (() => { - class APIResource4 { - constructor(client) { - this._client = client; + /** + * Users with pull access in a repository can access a combined view of commit + * statuses for a given ref. The ref can be a SHA, a branch name, or a tag name. + * + * Additionally, a combined `state` is returned. The `state` is one of: + * + * - **failure** if any of the contexts report as `error` or `failure` + * - **pending** if there are no statuses or a context is `pending` + * - **success** if the latest status for all contexts is `success` + * + * @example + * ```ts + * const response = await client.repos.commits.retrieveStatus( + * 'ref', + * { owner: 'owner', repo: 'repo' }, + * ); + * ``` + */ + retrieveStatus(ref, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/commits/${ref}/status`, { query, ...options }); } } - APIResource4._key = []; - return APIResource4; + BaseCommits4._key = Object.freeze(["repos", "commits"]); + return BaseCommits4; })(); -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/utils/values.mjs -var startsWithSchemeRegexp2 = /^[a-z][a-z0-9+.-]*:/i; -var isAbsoluteURL2 = (url) => { - return startsWithSchemeRegexp2.test(url); -}; -var isArray2 = (val) => (isArray2 = Array.isArray, isArray2(val)); -var isReadonlyArray2 = isArray2; -function isEmptyObj2(obj) { - if (!obj) - return true; - for (const _k in obj) - return false; - return true; -} -function hasOwn2(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} -var validatePositiveInteger2 = (name, n) => { - if (typeof n !== "number" || !Number.isInteger(n)) { - throw new GitLabError(`${name} must be an integer`); - } - if (n < 0) { - throw new GitLabError(`${name} must be a positive integer`); - } - return n; -}; -var safeJSON2 = (text) => { - try { - return JSON.parse(text); - } catch (err) { - return void 0; - } -}; - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/headers.mjs +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/headers.mjs var brand_privateNullableHeaders2 = /* @__PURE__ */ Symbol("brand.privateNullableHeaders"); function* iterateHeaders2(headers) { if (!headers) @@ -13582,1744 +12114,2468 @@ var buildHeaders2 = (newHeaders) => { return { [brand_privateNullableHeaders2]: true, values: targetHeaders, nulls: nullHeaders }; }; -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/utils/path.mjs -function encodeURIPath2(str) { - return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); -} -var EMPTY2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); -var createPathTagFunction2 = (pathEncoder = encodeURIPath2) => function path7(statics, ...params) { - if (statics.length === 1) - return statics[0]; - let postPath = false; - const invalidSegments = []; - const path8 = statics.reduce((previousValue, currentValue, index) => { - if (/[?#]/.test(currentValue)) { - postPath = true; - } - const value = params[index]; - let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value); - if (index !== params.length && (value == null || typeof value === "object" && // handle values from other realms - value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY2) ?? EMPTY2)?.toString)) { - encoded = value + ""; - invalidSegments.push({ - start: previousValue.length + currentValue.length, - length: encoded.length, - error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter` - }); - } - return previousValue + currentValue + (index === params.length ? "" : encoded); - }, ""); - const pathOnly = path8.split(/[?#]/, 1)[0]; - const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; - let match; - while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) { - invalidSegments.push({ - start: match.index, - length: match[0].length, - error: `Value "${match[0]}" can't be safely passed as a path parameter` - }); - } - invalidSegments.sort((a, b) => a.start - b.start); - if (invalidSegments.length > 0) { - let lastEnd = 0; - const underline = invalidSegments.reduce((acc, segment) => { - const spaces = " ".repeat(segment.start - lastEnd); - const arrows = "^".repeat(segment.length); - lastEnd = segment.start + segment.length; - return acc + spaces + arrows; - }, ""); - throw new GitLabError(`Path parameters result in path with invalid segments: -${invalidSegments.map((e) => e.error).join("\n")} -${path8} -${underline}`); - } - return path8; -}; -var path2 = /* @__PURE__ */ createPathTagFunction2(encodeURIPath2); - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/resources/projects/merge-requests/notes/notes.mjs -var BaseNotes2 = /* @__PURE__ */ (() => { - class BaseNotes13 extends APIResource2 { +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/resources/repos/issues/comments/comments.mjs +var BaseComments2 = /* @__PURE__ */ (() => { + class BaseComments8 extends APIResource2 { /** - * Create a new merge request note + * You can use the REST API to create comments on issues and pull requests. Every + * pull request is an issue, but not every issue is a pull request. + * + * This endpoint triggers + * [notifications](https://docs.github.com/github/managing-subscriptions-and-notifications-on-github/about-notifications). + * Creating content too quickly using this endpoint may result in secondary rate + * limiting. For more information, see + * "[Rate limits for the API](https://docs.github.com/rest/using-the-rest-api/rate-limits-for-the-rest-api#about-secondary-rate-limits)" + * and + * "[Best practices for using the REST API](https://docs.github.com/rest/guides/best-practices-for-using-the-rest-api)." + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response + * will include `body`. This is the default if you do not pass any specific media + * type. + * - **`application/vnd.github.text+json`**: Returns a text only representation of + * the markdown body. Response will include `body_text`. + * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's + * markdown. Response will include `body_html`. + * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML + * representations. Response will include `body`, `body_text`, and `body_html`. * * @example * ```ts - * const apiEntitiesNote = - * await client.projects.mergeRequests.notes.create(0, { - * id: 'id', - * body: 'body', + * const issueComment = + * await client.repos.issues.comments.create(0, { + * owner: 'owner', + * repo: 'repo', + * body: 'Me too', * }); * ``` */ - create(noteableID, params, options) { - const { id, ...body } = params; - return this._client.post(path2`/projects/${id}/merge_requests/${noteableID}/notes`, { body, ...options }); + create(issueNumber, params, options) { + const { owner = this._client.owner, repo = this._client.repo, ...body } = params; + return this._client.post(path2`/repos/${owner}/${repo}/issues/${issueNumber}/comments`, { + body, + ...options + }); } /** - * Get a single merge request note + * You can use the REST API to get comments on issues and pull requests. Every pull + * request is an issue, but not every issue is a pull request. + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response + * will include `body`. This is the default if you do not pass any specific media + * type. + * - **`application/vnd.github.text+json`**: Returns a text only representation of + * the markdown body. Response will include `body_text`. + * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's + * markdown. Response will include `body_html`. + * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML + * representations. Response will include `body`, `body_text`, and `body_html`. * * @example * ```ts - * const apiEntitiesNote = - * await client.projects.mergeRequests.notes.retrieve(0, { - * id: 'id', - * noteable_id: 0, + * const issueComment = + * await client.repos.issues.comments.retrieve(0, { + * owner: 'owner', + * repo: 'repo', * }); * ``` */ - retrieve(noteID, params, options) { - const { id, noteable_id } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${noteable_id}/notes/${noteID}`, options); + retrieve(commentID, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/issues/comments/${commentID}`, options); } /** - * Update an existing merge request note + * You can use the REST API to update comments on issues and pull requests. Every + * pull request is an issue, but not every issue is a pull request. + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response + * will include `body`. This is the default if you do not pass any specific media + * type. + * - **`application/vnd.github.text+json`**: Returns a text only representation of + * the markdown body. Response will include `body_text`. + * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's + * markdown. Response will include `body_html`. + * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML + * representations. Response will include `body`, `body_text`, and `body_html`. * * @example * ```ts - * const apiEntitiesNote = - * await client.projects.mergeRequests.notes.update(0, { - * id: 'id', - * noteable_id: 0, + * const issueComment = + * await client.repos.issues.comments.update(0, { + * owner: 'owner', + * repo: 'repo', + * body: 'Me too', * }); * ``` */ - update(noteID, params, options) { - const { id, noteable_id, ...body } = params; - return this._client.put(path2`/projects/${id}/merge_requests/${noteable_id}/notes/${noteID}`, { + update(commentID, params, options) { + const { owner = this._client.owner, repo = this._client.repo, ...body } = params; + return this._client.patch(path2`/repos/${owner}/${repo}/issues/comments/${commentID}`, { body, ...options }); } + async upsertBasedOnBodyMatch(issueNumber, { bodyIncludes, createParams, updateParams, options }) { + const comments = await this.list(issueNumber); + const match = comments.data.find((comment) => comment.body?.includes(bodyIncludes)); + if (match) { + return this.update(match.id, updateParams, options); + } else { + return this.create(issueNumber, createParams, options); + } + } /** - * Get a list of merge request notes + * You can use the REST API to list comments on issues and pull requests. Every + * pull request is an issue, but not every issue is a pull request. + * + * Issue comments are ordered by ascending ID. + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response + * will include `body`. This is the default if you do not pass any specific media + * type. + * - **`application/vnd.github.text+json`**: Returns a text only representation of + * the markdown body. Response will include `body_text`. + * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's + * markdown. Response will include `body_html`. + * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML + * representations. Response will include `body`, `body_text`, and `body_html`. * * @example * ```ts - * const apiEntitiesNote = - * await client.projects.mergeRequests.notes.list(0, { - * id: 'id', - * }); + * // Automatically fetches more pages as needed. + * for await (const issueComment of client.repos.issues.comments.list( + * 0, + * { owner: 'owner', repo: 'repo' }, + * )) { + * // ... + * } * ``` */ - list(noteableID, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${noteableID}/notes`, { query, ...options }); + list(issueNumber, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.getAPIList(path2`/repos/${owner}/${repo}/issues/${issueNumber}/comments`, NumberedPage, { query, ...options }); } /** - * Delete a merge request note + * You can use the REST API to delete comments on issues and pull requests. Every + * pull request is an issue, but not every issue is a pull request. * * @example * ```ts - * const apiEntitiesNote = - * await client.projects.mergeRequests.notes.delete(0, { - * id: 'id', - * noteable_id: 0, - * }); + * await client.repos.issues.comments.delete(0, { + * owner: 'owner', + * repo: 'repo', + * }); * ``` */ - delete(noteID, params, options) { - const { id, noteable_id } = params; - return this._client.delete(path2`/projects/${id}/merge_requests/${noteable_id}/notes/${noteID}`, options); + delete(commentID, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; + return this._client.delete(path2`/repos/${owner}/${repo}/issues/comments/${commentID}`, { + ...options, + headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + }); } } - BaseNotes13._key = Object.freeze([ - "projects", - "mergeRequests", - "notes" + BaseComments8._key = Object.freeze([ + "repos", + "issues", + "comments" ]); - return BaseNotes13; + return BaseComments8; })(); -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/resources/projects/merge-requests/merge-requests.mjs -var BaseMergeRequests = /* @__PURE__ */ (() => { - class BaseMergeRequests3 extends APIResource2 { +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/resources/repos/pulls/pulls.mjs +var BasePulls = /* @__PURE__ */ (() => { + class BasePulls2 extends APIResource2 { /** - * Create a new merge request. + * Draft pull requests are available in public repositories with GitHub Free and + * GitHub Free for organizations, GitHub Pro, and legacy per-repository billing + * plans, and in public and private repositories with GitHub Team and GitHub + * Enterprise Cloud. For more information, see + * [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) + * in the GitHub Help documentation. * - * @example - * ```ts - * const apiEntitiesMergeRequest = - * await client.projects.mergeRequests.create('string', { - * source_branch: 'source_branch', - * target_branch: 'target_branch', - * title: 'title', - * }); - * ``` - */ - create(id, body, options) { - return this._client.post(path2`/projects/${id}/merge_requests`, { body, ...options }); - } - /** - * Shows information about a single merge request. Note: the `changes_count` value - * in the response is a string, not an integer. This is because when an merge - * request has too many changes to display and store, it is capped at 1,000. In - * that case, the API returns the string `"1000+"` for the changes count. + * To open or update a pull request in a public repository, you must have write + * access to the head or the source branch. For organization-owned repositories, + * you must be a member of the organization that owns the repository to open or + * update a pull request. * - * @example - * ```ts - * const apiEntitiesMergeRequest = - * await client.projects.mergeRequests.retrieve(0, { - * id: 'string', - * }); - * ``` - */ - retrieve(mergeRequestIid, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${mergeRequestIid}`, { query, ...options }); - } - /** - * Updates an existing merge request. You can change the target branch, title, or - * even close the merge request. + * This endpoint triggers + * [notifications](https://docs.github.com/github/managing-subscriptions-and-notifications-on-github/about-notifications). + * Creating content too quickly using this endpoint may result in secondary rate + * limiting. For more information, see + * "[Rate limits for the API](https://docs.github.com/rest/using-the-rest-api/rate-limits-for-the-rest-api#about-secondary-rate-limits)" + * and + * "[Best practices for using the REST API](https://docs.github.com/rest/guides/best-practices-for-using-the-rest-api)." + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response + * will include `body`. This is the default if you do not pass any specific media + * type. + * - **`application/vnd.github.text+json`**: Returns a text only representation of + * the markdown body. Response will include `body_text`. + * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's + * markdown. Response will include `body_html`. + * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML + * representations. Response will include `body`, `body_text`, and `body_html`. * * @example * ```ts - * const apiEntitiesMergeRequest = - * await client.projects.mergeRequests.update(0, { - * id: 'string', - * }); + * const pullRequest = await client.repos.pulls.create({ + * owner: 'owner', + * repo: 'repo', + * base: 'master', + * head: 'octocat:new-feature', + * body: 'Please pull these awesome changes in!', + * title: 'Amazing new feature', + * }); * ``` */ - update(mergeRequestIid, params, options) { - const { id, ...body } = params; - return this._client.put(path2`/projects/${id}/merge_requests/${mergeRequestIid}`, { body, ...options }); + create(params, options) { + const { owner = this._client.owner, repo = this._client.repo, ...body } = params; + return this._client.post(path2`/repos/${owner}/${repo}/pulls`, { body, ...options }); } /** - * Get all merge requests for this project. + * Draft pull requests are available in public repositories with GitHub Free and + * GitHub Free for organizations, GitHub Pro, and legacy per-repository billing + * plans, and in public and private repositories with GitHub Team and GitHub + * Enterprise Cloud. For more information, see + * [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) + * in the GitHub Help documentation. + * + * Lists details of a pull request by providing its number. + * + * When you get, + * [create](https://docs.github.com/rest/pulls/pulls/#create-a-pull-request), or + * [edit](https://docs.github.com/rest/pulls/pulls#update-a-pull-request) a pull + * request, GitHub creates a merge commit to test whether the pull request can be + * automatically merged into the base branch. This test commit is not added to the + * base branch or the head branch. You can review the status of the test commit + * using the `mergeable` key. For more information, see + * "[Checking mergeability of pull requests](https://docs.github.com/rest/guides/getting-started-with-the-git-database-api#checking-mergeability-of-pull-requests)". + * + * The value of the `mergeable` attribute can be `true`, `false`, or `null`. If the + * value is `null`, then GitHub has started a background job to compute the + * mergeability. After giving the job time to complete, resubmit the request. When + * the job finishes, you will see a non-`null` value for the `mergeable` attribute + * in the response. If `mergeable` is `true`, then `merge_commit_sha` will be the + * SHA of the _test_ merge commit. + * + * The value of the `merge_commit_sha` attribute changes depending on the state of + * the pull request. Before merging a pull request, the `merge_commit_sha` + * attribute holds the SHA of the _test_ merge commit. After merging a pull + * request, the `merge_commit_sha` attribute changes depending on how you merged + * the pull request: + * + * - If merged as a + * [merge commit](https://docs.github.com/articles/about-merge-methods-on-github/), + * `merge_commit_sha` represents the SHA of the merge commit. + * - If merged via a + * [squash](https://docs.github.com/articles/about-merge-methods-on-github/#squashing-your-merge-commits), + * `merge_commit_sha` represents the SHA of the squashed commit on the base + * branch. + * - If + * [rebased](https://docs.github.com/articles/about-merge-methods-on-github/#rebasing-and-merging-your-commits), + * `merge_commit_sha` represents the commit that the base branch was updated to. + * + * Pass the appropriate + * [media type](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types) + * to fetch diff and patch formats. + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response + * will include `body`. This is the default if you do not pass any specific media + * type. + * - **`application/vnd.github.text+json`**: Returns a text only representation of + * the markdown body. Response will include `body_text`. + * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's + * markdown. Response will include `body_html`. + * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML + * representations. Response will include `body`, `body_text`, and `body_html`. + * - **`application/vnd.github.diff`**: For more information, see + * "[git-diff](https://git-scm.com/docs/git-diff)" in the Git documentation. If a + * diff is corrupt, contact us through the + * [GitHub Support portal](https://support.github.com/). Include the repository + * name and pull request ID in your message. * * @example * ```ts - * const apiEntitiesMergeRequestBasics = - * await client.projects.mergeRequests.list('string'); + * const pullRequest = await client.repos.pulls.retrieve(0, { + * owner: 'owner', + * repo: 'repo', + * }); * ``` */ - list(id, query = {}, options) { - return this._client.get(path2`/projects/${id}/merge_requests`, { query, ...options }); + retrieve(pullNumber, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/pulls/${pullNumber}`, options); } /** - * Only for administrators and project owners. Deletes the merge request in - * question. + * Draft pull requests are available in public repositories with GitHub Free and + * GitHub Free for organizations, GitHub Pro, and legacy per-repository billing + * plans, and in public and private repositories with GitHub Team and GitHub + * Enterprise Cloud. For more information, see + * [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) + * in the GitHub Help documentation. + * + * To open or update a pull request in a public repository, you must have write + * access to the head or the source branch. For organization-owned repositories, + * you must be a member of the organization that owns the repository to open or + * update a pull request. + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response + * will include `body`. This is the default if you do not pass any specific media + * type. + * - **`application/vnd.github.text+json`**: Returns a text only representation of + * the markdown body. Response will include `body_text`. + * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's + * markdown. Response will include `body_html`. + * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML + * representations. Response will include `body`, `body_text`, and `body_html`. * * @example * ```ts - * await client.projects.mergeRequests.delete(0, { - * id: 'string', + * const pullRequest = await client.repos.pulls.update(0, { + * owner: 'owner', + * repo: 'repo', + * base: 'master', + * body: 'updated body', + * state: 'open', + * title: 'new title', * }); * ``` */ - delete(mergeRequestIid, params, options) { - const { id } = params; - return this._client.delete(path2`/projects/${id}/merge_requests/${mergeRequestIid}`, { - ...options, - headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) - }); + update(pullNumber, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...body } = params ?? {}; + return this._client.patch(path2`/repos/${owner}/${repo}/pulls/${pullNumber}`, { body, ...options }); } /** - * Adds spent time for this merge_request. + * Lists pull requests in a specified repository. + * + * Draft pull requests are available in public repositories with GitHub Free and + * GitHub Free for organizations, GitHub Pro, and legacy per-repository billing + * plans, and in public and private repositories with GitHub Team and GitHub + * Enterprise Cloud. For more information, see + * [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) + * in the GitHub Help documentation. + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response + * will include `body`. This is the default if you do not pass any specific media + * type. + * - **`application/vnd.github.text+json`**: Returns a text only representation of + * the markdown body. Response will include `body_text`. + * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's + * markdown. Response will include `body_html`. + * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML + * representations. Response will include `body`, `body_text`, and `body_html`. * * @example * ```ts - * const apiEntitiesIssuableTimeStats = - * await client.projects.mergeRequests.addSpentTime(0, { - * id: 'string', - * duration: 'duration', - * }); + * // Automatically fetches more pages as needed. + * for await (const pullRequestSimple of client.repos.pulls.list( + * { owner: 'owner', repo: 'repo' }, + * )) { + * // ... + * } * ``` */ - addSpentTime(mergeRequestIid, params, options) { - const { id, ...body } = params; - return this._client.post(path2`/projects/${id}/merge_requests/${mergeRequestIid}/add_spent_time`, { - body, + list(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.getAPIList(path2`/repos/${owner}/${repo}/pulls`, NumberedPage, { + query, ...options }); } /** - * Approve a merge request + * Creates a codespace owned by the authenticated user for the specified pull + * request. + * + * OAuth app tokens and personal access tokens (classic) need the `codespace` scope + * to use this endpoint. * * @example * ```ts - * const apiEntitiesMergeRequestApprovals = - * await client.projects.mergeRequests.approve(0, { - * id: 'id', - * }); + * const codespace = await client.repos.pulls.createCodespace( + * 0, + * { owner: 'owner', repo: 'repo' }, + * ); * ``` */ - approve(mergeRequestIid, params, options) { - const { id, ...body } = params; - return this._client.post(path2`/projects/${id}/merge_requests/${mergeRequestIid}/approve`, { + createCodespace(pullNumber, params, options) { + const { owner = this._client.owner, repo = this._client.repo, ...body } = params; + return this._client.post(path2`/repos/${owner}/${repo}/pulls/${pullNumber}/codespaces`, { body, ...options }); } /** - * Cancel merge if "Merge When Pipeline Succeeds" is enabled + * Creates a review comment on the diff of a specified pull request. To add a + * regular comment to a pull request timeline, see + * "[Create an issue comment](https://docs.github.com/rest/issues/comments#create-an-issue-comment)." * - * @example - * ```ts - * const apiEntitiesMergeRequest = - * await client.projects.mergeRequests.cancelMergeWhenPipelineSucceeds( - * 0, - * { id: 'string' }, - * ); - * ``` - */ - cancelMergeWhenPipelineSucceeds(mergeRequestIid, params, options) { - const { id } = params; - return this._client.post(path2`/projects/${id}/merge_requests/${mergeRequestIid}/cancel_merge_when_pipeline_succeeds`, options); - } - /** - * Resets the total spent time for this merge_request to 0 seconds. + * If your comment applies to more than one line in the pull request diff, you + * should use the parameters `line`, `side`, and optionally `start_line` and + * `start_side` in your request. * - * @example - * ```ts - * const apiEntitiesIssuableTimeStats = - * await client.projects.mergeRequests.resetSpentTime(0, { - * id: 'string', - * }); - * ``` - */ - resetSpentTime(mergeRequestIid, params, options) { - const { id } = params; - return this._client.post(path2`/projects/${id}/merge_requests/${mergeRequestIid}/reset_spent_time`, options); - } - /** - * Resets the estimated time for this merge_request to 0 seconds. + * The `position` parameter is closing down. If you use `position`, the `line`, + * `side`, `start_line`, and `start_side` parameters are not required. * - * @example - * ```ts - * const apiEntitiesIssuableTimeStats = - * await client.projects.mergeRequests.resetTimeEstimate(0, { - * id: 'string', - * }); - * ``` - */ - resetTimeEstimate(mergeRequestIid, params, options) { - const { id } = params; - return this._client.post(path2`/projects/${id}/merge_requests/${mergeRequestIid}/reset_time_estimate`, options); - } - /** - * List approval rules for merge request + * This endpoint triggers + * [notifications](https://docs.github.com/github/managing-subscriptions-and-notifications-on-github/about-notifications). + * Creating content too quickly using this endpoint may result in secondary rate + * limiting. For more information, see + * "[Rate limits for the API](https://docs.github.com/rest/using-the-rest-api/rate-limits-for-the-rest-api#about-secondary-rate-limits)" + * and + * "[Best practices for using the REST API](https://docs.github.com/rest/guides/best-practices-for-using-the-rest-api)." * - * @example - * ```ts - * await client.projects.mergeRequests.retrieveApprovalSettings( - * 0, - * { id: 'string' }, - * ); - * ``` - */ - retrieveApprovalSettings(mergeRequestIid, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${mergeRequestIid}/approval_settings`, { - query, - ...options, - headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) - }); - } - /** - * Get approval state of merge request + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." * - * @example - * ```ts - * const response = - * await client.projects.mergeRequests.retrieveApprovalState( - * 0, - * { id: 'string' }, - * ); - * ``` - */ - retrieveApprovalState(mergeRequestIid, params, options) { - const { id } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${mergeRequestIid}/approval_state`, options); - } - /** - * Get all merge requests are blockees for this merge request + * - **`application/vnd.github-commitcomment.raw+json`**: Returns the raw markdown + * body. Response will include `body`. This is the default if you do not pass any + * specific media type. + * - **`application/vnd.github-commitcomment.text+json`**: Returns a text only + * representation of the markdown body. Response will include `body_text`. + * - **`application/vnd.github-commitcomment.html+json`**: Returns HTML rendered + * from the body's markdown. Response will include `body_html`. + * - **`application/vnd.github-commitcomment.full+json`**: Returns raw, text, and + * HTML representations. Response will include `body`, `body_text`, and + * `body_html`. * * @example * ```ts - * const apiEntitiesMergeRequestDependency = - * await client.projects.mergeRequests.retrieveBlockees(0, { - * id: 'string', - * }); + * const response = await client.repos.pulls.createComment(0, { + * owner: 'owner', + * repo: 'repo', + * body: 'Great stuff!', + * commit_id: '6dcb09b5b57875f334f61aebed695e2e4193db5e', + * path: 'file1.txt', + * line: 2, + * side: 'RIGHT', + * start_line: 1, + * start_side: 'RIGHT', + * }); * ``` */ - retrieveBlockees(mergeRequestIid, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${mergeRequestIid}/blockees`, { - query, + createComment(pullNumber, params, options) { + const { owner = this._client.owner, repo = this._client.repo, ...body } = params; + return this._client.post(path2`/repos/${owner}/${repo}/pulls/${pullNumber}/comments`, { + body, ...options }); } /** - * Shows information about the merge request including its files and changes. + * Lists all review comments for a specified pull request. By default, review + * comments are in ascending order by ID. * - * @example - * ```ts - * const response = - * await client.projects.mergeRequests.retrieveChanges(0, { - * id: 'string', - * }); - * ``` - */ - retrieveChanges(mergeRequestIid, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${mergeRequestIid}/changes`, { - query, - ...options - }); - } - /** - * Get all the issues that would be closed by merging the provided merge request. + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github-commitcomment.raw+json`**: Returns the raw markdown + * body. Response will include `body`. This is the default if you do not pass any + * specific media type. + * - **`application/vnd.github-commitcomment.text+json`**: Returns a text only + * representation of the markdown body. Response will include `body_text`. + * - **`application/vnd.github-commitcomment.html+json`**: Returns HTML rendered + * from the body's markdown. Response will include `body_html`. + * - **`application/vnd.github-commitcomment.full+json`**: Returns raw, text, and + * HTML representations. Response will include `body`, `body_text`, and + * `body_html`. * * @example * ```ts - * const response = - * await client.projects.mergeRequests.retrieveClosesIssues( - * 0, - * { id: 'string' }, - * ); + * // Automatically fetches more pages as needed. + * for await (const pullListCommentsResponse of client.repos.pulls.listComments( + * 0, + * { owner: 'owner', repo: 'repo' }, + * )) { + * // ... + * } * ``` */ - retrieveClosesIssues(mergeRequestIid, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${mergeRequestIid}/closes_issues`, { - query, - ...options - }); + listComments(pullNumber, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.getAPIList(path2`/repos/${owner}/${repo}/pulls/${pullNumber}/comments`, NumberedPage, { query, ...options }); } /** - * Get a list of merge request commits. + * Lists a maximum of 250 commits for a pull request. To receive a complete commit + * list for pull requests with more than 250 commits, use the + * [List commits](https://docs.github.com/rest/commits/commits#list-commits) + * endpoint. + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response + * will include `body`. This is the default if you do not pass any specific media + * type. + * - **`application/vnd.github.text+json`**: Returns a text only representation of + * the markdown body. Response will include `body_text`. + * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's + * markdown. Response will include `body_html`. + * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML + * representations. Response will include `body`, `body_text`, and `body_html`. * * @example * ```ts - * const apiEntitiesCommit = - * await client.projects.mergeRequests.retrieveCommits(0, { - * id: 'string', - * }); + * // Automatically fetches more pages as needed. + * for await (const commit of client.repos.pulls.listCommits( + * 0, + * { owner: 'owner', repo: 'repo' }, + * )) { + * // ... + * } * ``` */ - retrieveCommits(mergeRequestIid, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${mergeRequestIid}/commits`, { - query, - ...options - }); + listCommits(pullNumber, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.getAPIList(path2`/repos/${owner}/${repo}/pulls/${pullNumber}/commits`, NumberedPage, { query, ...options }); } /** - * Get a list of merge request diffs. + * Lists the files in a specified pull request. + * + * > [!NOTE] Responses include a maximum of 3000 files. The paginated response + * > returns 30 files per page by default. + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response + * will include `body`. This is the default if you do not pass any specific media + * type. + * - **`application/vnd.github.text+json`**: Returns a text only representation of + * the markdown body. Response will include `body_text`. + * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's + * markdown. Response will include `body_html`. + * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML + * representations. Response will include `body`, `body_text`, and `body_html`. * * @example * ```ts - * const apiEntitiesDiff = - * await client.projects.mergeRequests.retrieveDiffs(0, { - * id: 'string', - * }); + * // Automatically fetches more pages as needed. + * for await (const pullListFilesResponse of client.repos.pulls.listFiles( + * 0, + * { owner: 'owner', repo: 'repo' }, + * )) { + * // ... + * } * ``` */ - retrieveDiffs(mergeRequestIid, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${mergeRequestIid}/diffs`, { - query, - ...options - }); + listFiles(pullNumber, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.getAPIList(path2`/repos/${owner}/${repo}/pulls/${pullNumber}/files`, NumberedPage, { query, ...options }); } /** - * Returns the up to date merge-ref HEAD commit + * Updates the pull request branch with the latest upstream changes by merging HEAD + * from the base branch into the pull request branch. Note: If making a request on + * behalf of a GitHub App you must also have permissions to write the contents of + * the head repository. * * @example * ```ts - * await client.projects.mergeRequests.retrieveMergeRef(0, { - * id: 'string', + * const response = await client.repos.pulls.updateBranch(0, { + * owner: 'owner', + * repo: 'repo', + * expected_head_sha: + * '6dcb09b5b57875f334f61aebed695e2e4193db5e', * }); * ``` */ - retrieveMergeRef(mergeRequestIid, params, options) { - const { id } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${mergeRequestIid}/merge_ref`, { - ...options, - headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + updateBranch(pullNumber, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...body } = params ?? {}; + return this._client.put(path2`/repos/${owner}/${repo}/pulls/${pullNumber}/update-branch`, { + body, + ...options }); } - /** - * Get a list of merge request participants. - * - * @example - * ```ts - * const apiEntitiesUserBasic = - * await client.projects.mergeRequests.retrieveParticipants( - * 0, - * { id: 'string' }, - * ); - * ``` - */ - retrieveParticipants(mergeRequestIid, params, options) { - const { id } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${mergeRequestIid}/participants`, options); + } + BasePulls2._key = Object.freeze(["repos", "pulls"]); + return BasePulls2; +})(); + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/utils/uuid.mjs +var uuid42 = function() { + const { crypto: crypto2 } = globalThis; + if (crypto2?.randomUUID) { + uuid42 = crypto2.randomUUID.bind(crypto2); + return crypto2.randomUUID(); + } + const u8 = new Uint8Array(1); + const randomByte = crypto2 ? () => crypto2.getRandomValues(u8)[0] : () => Math.random() * 255 & 255; + return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16)); +}; + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/utils/sleep.mjs +var sleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/version.mjs +var VERSION2 = "0.25.1"; + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/detect-platform.mjs +function getDetectedPlatform2() { + if (typeof Deno !== "undefined" && Deno.build != null) { + return "deno"; + } + if (typeof EdgeRuntime !== "undefined") { + return "edge"; + } + if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") { + return "node"; + } + return "unknown"; +} +var getPlatformProperties2 = () => { + const detectedPlatform = getDetectedPlatform2(); + if (detectedPlatform === "deno") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION2, + "X-Stainless-OS": normalizePlatform2(Deno.build.os), + "X-Stainless-Arch": normalizeArch2(Deno.build.arch), + "X-Stainless-Runtime": "deno", + "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown" + }; + } + if (typeof EdgeRuntime !== "undefined") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION2, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": `other:${EdgeRuntime}`, + "X-Stainless-Runtime": "edge", + "X-Stainless-Runtime-Version": globalThis.process.version + }; + } + if (detectedPlatform === "node") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION2, + "X-Stainless-OS": normalizePlatform2(globalThis.process.platform ?? "unknown"), + "X-Stainless-Arch": normalizeArch2(globalThis.process.arch ?? "unknown"), + "X-Stainless-Runtime": "node", + "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown" + }; + } + const browserInfo = getBrowserInfo2(); + if (browserInfo) { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION2, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": "unknown", + "X-Stainless-Runtime": `browser:${browserInfo.browser}`, + "X-Stainless-Runtime-Version": browserInfo.version + }; + } + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION2, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": "unknown", + "X-Stainless-Runtime": "unknown", + "X-Stainless-Runtime-Version": "unknown" + }; +}; +function getBrowserInfo2() { + if (typeof navigator === "undefined" || !navigator) { + return null; + } + const browserPatterns = [ + { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ } + ]; + for (const { key, pattern } of browserPatterns) { + const match = pattern.exec(navigator.userAgent); + if (match) { + const major = match[1] || 0; + const minor = match[2] || 0; + const patch = match[3] || 0; + return { browser: key, version: `${major}.${minor}.${patch}` }; + } + } + return null; +} +var normalizeArch2 = (arch) => { + if (arch === "x32") + return "x32"; + if (arch === "x86_64" || arch === "x64") + return "x64"; + if (arch === "arm") + return "arm"; + if (arch === "aarch64" || arch === "arm64") + return "arm64"; + if (arch) + return `other:${arch}`; + return "unknown"; +}; +var normalizePlatform2 = (platform) => { + platform = platform.toLowerCase(); + if (platform.includes("ios")) + return "iOS"; + if (platform === "android") + return "Android"; + if (platform === "darwin") + return "MacOS"; + if (platform === "win32") + return "Windows"; + if (platform === "freebsd") + return "FreeBSD"; + if (platform === "openbsd") + return "OpenBSD"; + if (platform === "linux") + return "Linux"; + if (platform) + return `Other:${platform}`; + return "Unknown"; +}; +var _platformHeaders2; +var getPlatformHeaders2 = () => { + return _platformHeaders2 ?? (_platformHeaders2 = getPlatformProperties2()); +}; + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/shims.mjs +function getDefaultFetch2() { + if (typeof fetch !== "undefined") { + return fetch; + } + throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new GitHub({ fetch })` or polyfill the global, `globalThis.fetch = fetch`"); +} +function makeReadableStream2(...args) { + const ReadableStream = globalThis.ReadableStream; + if (typeof ReadableStream === "undefined") { + throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`"); + } + return new ReadableStream(...args); +} +function ReadableStreamFrom2(iterable) { + let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); + return makeReadableStream2({ + start() { + }, + async pull(controller) { + const { done, value } = await iter.next(); + if (done) { + controller.close(); + } else { + controller.enqueue(value); + } + }, + async cancel() { + await iter.return?.(); + } + }); +} +async function CancelReadableStream2(stream) { + if (stream === null || typeof stream !== "object") + return; + if (stream[Symbol.asyncIterator]) { + await stream[Symbol.asyncIterator]().return?.(); + return; + } + const reader = stream.getReader(); + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; +} + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/request-options.mjs +var FallbackEncoder2 = ({ headers, body }) => { + return { + bodyHeaders: { + "content-type": "application/json" + }, + body: JSON.stringify(body) + }; +}; + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/qs/formats.mjs +var default_format2 = "RFC3986"; +var default_formatter2 = (v) => String(v); +var formatters2 = { + RFC1738: (v) => String(v).replace(/%20/g, "+"), + RFC3986: default_formatter2 +}; +var RFC17382 = "RFC1738"; + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/qs/utils.mjs +var has2 = (obj, key) => (has2 = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has2(obj, key)); +var hex_table2 = /* @__PURE__ */ (() => { + const array = []; + for (let i = 0; i < 256; ++i) { + array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase()); + } + return array; +})(); +var limit2 = 1024; +var encode2 = (str, _defaultEncoder, charset, _kind, format) => { + if (str.length === 0) { + return str; + } + let string = str; + if (typeof str === "symbol") { + string = Symbol.prototype.toString.call(str); + } else if (typeof str !== "string") { + string = String(str); + } + if (charset === "iso-8859-1") { + return escape(string).replace(/%u[0-9a-f]{4}/gi, function($0) { + return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; + }); + } + let out = ""; + for (let j = 0; j < string.length; j += limit2) { + const segment = string.length >= limit2 ? string.slice(j, j + limit2) : string; + const arr = []; + for (let i = 0; i < segment.length; ++i) { + let c = segment.charCodeAt(i); + if (c === 45 || // - + c === 46 || // . + c === 95 || // _ + c === 126 || // ~ + c >= 48 && c <= 57 || // 0-9 + c >= 65 && c <= 90 || // a-z + c >= 97 && c <= 122 || // A-Z + format === RFC17382 && (c === 40 || c === 41)) { + arr[arr.length] = segment.charAt(i); + continue; + } + if (c < 128) { + arr[arr.length] = hex_table2[c]; + continue; + } + if (c < 2048) { + arr[arr.length] = hex_table2[192 | c >> 6] + hex_table2[128 | c & 63]; + continue; + } + if (c < 55296 || c >= 57344) { + arr[arr.length] = hex_table2[224 | c >> 12] + hex_table2[128 | c >> 6 & 63] + hex_table2[128 | c & 63]; + continue; + } + i += 1; + c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023); + arr[arr.length] = hex_table2[240 | c >> 18] + hex_table2[128 | c >> 12 & 63] + hex_table2[128 | c >> 6 & 63] + hex_table2[128 | c & 63]; } - /** - * Get the raw diffs of a merge request that can used programmatically. - * - * @example - * ```ts - * await client.projects.mergeRequests.retrieveRawDiffs(0, { - * id: 'string', - * }); - * ``` - */ - retrieveRawDiffs(mergeRequestIid, params, options) { - const { id } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${mergeRequestIid}/raw_diffs`, { - ...options, - headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) - }); + out += arr.join(""); + } + return out; +}; +function is_buffer2(obj) { + if (!obj || typeof obj !== "object") { + return false; + } + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +} +function maybe_map2(val, fn) { + if (isArray2(val)) { + const mapped = []; + for (let i = 0; i < val.length; i += 1) { + mapped.push(fn(val[i])); } - /** - * Get all the related issues from title, description, commits, comments and - * discussions of the merge request. - * - * @example - * ```ts - * await client.projects.mergeRequests.retrieveRelatedIssues( - * 0, - * { id: 'string' }, - * ); - * ``` - */ - retrieveRelatedIssues(mergeRequestIid, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${mergeRequestIid}/related_issues`, { - query, - ...options, - headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) - }); + return mapped; + } + return fn(val); +} + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/qs/stringify.mjs +var array_prefix_generators2 = { + brackets(prefix) { + return String(prefix) + "[]"; + }, + comma: "comma", + indices(prefix, key) { + return String(prefix) + "[" + key + "]"; + }, + repeat(prefix) { + return String(prefix); + } +}; +var push_to_array2 = function(arr, value_or_array) { + Array.prototype.push.apply(arr, isArray2(value_or_array) ? value_or_array : [value_or_array]); +}; +var toISOString2; +var defaults2 = { + addQueryPrefix: false, + allowDots: false, + allowEmptyArrays: false, + arrayFormat: "indices", + charset: "utf-8", + charsetSentinel: false, + delimiter: "&", + encode: true, + encodeDotInKeys: false, + encoder: encode2, + encodeValuesOnly: false, + format: default_format2, + formatter: default_formatter2, + /** @deprecated */ + indices: false, + serializeDate(date) { + return (toISOString2 ?? (toISOString2 = Function.prototype.call.bind(Date.prototype.toISOString)))(date); + }, + skipNulls: false, + strictNullHandling: false +}; +function is_non_nullish_primitive2(v) { + return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint"; +} +var sentinel2 = {}; +function inner_stringify2(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { + let obj = object; + let tmp_sc = sideChannel; + let step = 0; + let find_flag = false; + while ((tmp_sc = tmp_sc.get(sentinel2)) !== void 0 && !find_flag) { + const pos = tmp_sc.get(object); + step += 1; + if (typeof pos !== "undefined") { + if (pos === step) { + throw new RangeError("Cyclic object value"); + } else { + find_flag = true; + } } - /** - * Get a list of merge request reviewers. - * - * @example - * ```ts - * const response = - * await client.projects.mergeRequests.retrieveReviewers(0, { - * id: 'string', - * }); - * ``` - */ - retrieveReviewers(mergeRequestIid, params, options) { - const { id } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${mergeRequestIid}/reviewers`, options); + if (typeof tmp_sc.get(sentinel2) === "undefined") { + step = 0; } - /** - * Get time tracking stats - * - * @example - * ```ts - * const apiEntitiesIssuableTimeStats = - * await client.projects.mergeRequests.retrieveTimeStats(0, { - * id: 'string', - * }); - * ``` - */ - retrieveTimeStats(mergeRequestIid, params, options) { - const { id } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${mergeRequestIid}/time_stats`, options); + } + if (typeof filter === "function") { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate?.(obj); + } else if (generateArrayPrefix === "comma" && isArray2(obj)) { + obj = maybe_map2(obj, function(value) { + if (value instanceof Date) { + return serializeDate?.(value); + } + return value; + }); + } + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? ( + // @ts-expect-error + encoder(prefix, defaults2.encoder, charset, "key", format) + ) : prefix; } - /** - * Set status of an external status check - * - * @example - * ```ts - * const response = - * await client.projects.mergeRequests.statusCheckResponses( - * 1, - * { - * id: '1', - * external_status_check_id: 1, - * sha: '5957a570eee0ac4580ec027fb874ad7514d1e576', - * status: 'passed', - * }, - * ); - * ``` - */ - statusCheckResponses(mergeRequestIid, params, options) { - const { id, ...body } = params; - return this._client.post(path2`/projects/${id}/merge_requests/${mergeRequestIid}/status_check_responses`, { - body, - ...options - }); + obj = ""; + } + if (is_non_nullish_primitive2(obj) || is_buffer2(obj)) { + if (encoder) { + const key_value = encodeValuesOnly ? prefix : encoder(prefix, defaults2.encoder, charset, "key", format); + return [ + formatter?.(key_value) + "=" + // @ts-expect-error + formatter?.(encoder(obj, defaults2.encoder, charset, "value", format)) + ]; } - /** - * Subscribe to a resource - * - * @example - * ```ts - * const apiEntitiesMergeRequest = - * await client.projects.mergeRequests.subscribe( - * 'subscribable_id', - * { id: 'id' }, - * ); - * ``` - */ - subscribe(subscribableID, params, options) { - const { id } = params; - return this._client.post(path2`/projects/${id}/merge_requests/${subscribableID}/subscribe`, options); + return [formatter?.(prefix) + "=" + formatter?.(String(obj))]; + } + const values = []; + if (typeof obj === "undefined") { + return values; + } + let obj_keys; + if (generateArrayPrefix === "comma" && isArray2(obj)) { + if (encodeValuesOnly && encoder) { + obj = maybe_map2(obj, encoder); } - /** - * Sets an estimated time of work for this merge_request. - * - * @example - * ```ts - * const apiEntitiesIssuableTimeStats = - * await client.projects.mergeRequests.timeEstimate(0, { - * id: 'string', - * duration: '3h30m', - * }); - * ``` - */ - timeEstimate(mergeRequestIid, params, options) { - const { id, ...body } = params; - return this._client.post(path2`/projects/${id}/merge_requests/${mergeRequestIid}/time_estimate`, { - body, - ...options - }); + obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; + } else if (isArray2(filter)) { + obj_keys = filter; + } else { + const keys = Object.keys(obj); + obj_keys = sort ? keys.sort(sort) : keys; + } + const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix); + const adjusted_prefix = commaRoundTrip && isArray2(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix; + if (allowEmptyArrays && isArray2(obj) && obj.length === 0) { + return adjusted_prefix + "[]"; + } + for (let j = 0; j < obj_keys.length; ++j) { + const key = obj_keys[j]; + const value = ( + // @ts-ignore + typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key] + ); + if (skipNulls && value === null) { + continue; } - /** - * Create a to-do item on an issuable - * - * @example - * ```ts - * const apiEntitiesTodo = - * await client.projects.mergeRequests.todo(0, { id: 'id' }); - * ``` - */ - todo(mergeRequestIid, params, options) { - const { id } = params; - return this._client.post(path2`/projects/${id}/merge_requests/${mergeRequestIid}/todo`, options); + const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key; + const key_prefix = isArray2(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]"); + sideChannel.set(object, step); + const valueSideChannel = /* @__PURE__ */ new WeakMap(); + valueSideChannel.set(sentinel2, sideChannel); + push_to_array2(values, inner_stringify2( + value, + key_prefix, + generateArrayPrefix, + commaRoundTrip, + allowEmptyArrays, + strictNullHandling, + skipNulls, + encodeDotInKeys, + // @ts-ignore + generateArrayPrefix === "comma" && encodeValuesOnly && isArray2(obj) ? null : encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + valueSideChannel + )); + } + return values; +} +function normalize_stringify_options2(opts = defaults2) { + if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") { + throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); + } + if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") { + throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided"); + } + if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") { + throw new TypeError("Encoder has to be a function."); + } + const charset = opts.charset || defaults2.charset; + if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { + throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); + } + let format = default_format2; + if (typeof opts.format !== "undefined") { + if (!has2(formatters2, opts.format)) { + throw new TypeError("Unknown format option provided."); + } + format = opts.format; + } + const formatter = formatters2[format]; + let filter = defaults2.filter; + if (typeof opts.filter === "function" || isArray2(opts.filter)) { + filter = opts.filter; + } + let arrayFormat; + if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators2) { + arrayFormat = opts.arrayFormat; + } else if ("indices" in opts) { + arrayFormat = opts.indices ? "indices" : "repeat"; + } else { + arrayFormat = defaults2.arrayFormat; + } + if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") { + throw new TypeError("`commaRoundTrip` must be a boolean, or absent"); + } + const allowDots = typeof opts.allowDots === "undefined" ? !!opts.encodeDotInKeys === true ? true : defaults2.allowDots : !!opts.allowDots; + return { + addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults2.addQueryPrefix, + // @ts-ignore + allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults2.allowEmptyArrays, + arrayFormat, + charset, + charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults2.charsetSentinel, + commaRoundTrip: !!opts.commaRoundTrip, + delimiter: typeof opts.delimiter === "undefined" ? defaults2.delimiter : opts.delimiter, + encode: typeof opts.encode === "boolean" ? opts.encode : defaults2.encode, + encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults2.encodeDotInKeys, + encoder: typeof opts.encoder === "function" ? opts.encoder : defaults2.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults2.encodeValuesOnly, + filter, + format, + formatter, + serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults2.serializeDate, + skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults2.skipNulls, + // @ts-ignore + sort: typeof opts.sort === "function" ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults2.strictNullHandling + }; +} +function stringify2(object, opts = {}) { + let obj = object; + const options = normalize_stringify_options2(opts); + let obj_keys; + let filter; + if (typeof options.filter === "function") { + filter = options.filter; + obj = filter("", obj); + } else if (isArray2(options.filter)) { + filter = options.filter; + obj_keys = filter; + } + const keys = []; + if (typeof obj !== "object" || obj === null) { + return ""; + } + const generateArrayPrefix = array_prefix_generators2[options.arrayFormat]; + const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip; + if (!obj_keys) { + obj_keys = Object.keys(obj); + } + if (options.sort) { + obj_keys.sort(options.sort); + } + const sideChannel = /* @__PURE__ */ new WeakMap(); + for (let i = 0; i < obj_keys.length; ++i) { + const key = obj_keys[i]; + if (options.skipNulls && obj[key] === null) { + continue; } - /** - * Remove an approval from a merge request - * - * @example - * ```ts - * const apiEntitiesMergeRequestApprovals = - * await client.projects.mergeRequests.unapprove(0, { - * id: 'id', - * }); - * ``` - */ - unapprove(mergeRequestIid, params, options) { - const { id } = params; - return this._client.post(path2`/projects/${id}/merge_requests/${mergeRequestIid}/unapprove`, options); + push_to_array2(keys, inner_stringify2( + obj[key], + key, + // @ts-expect-error + generateArrayPrefix, + commaRoundTrip, + options.allowEmptyArrays, + options.strictNullHandling, + options.skipNulls, + options.encodeDotInKeys, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.format, + options.formatter, + options.encodeValuesOnly, + options.charset, + sideChannel + )); + } + const joined = keys.join(options.delimiter); + let prefix = options.addQueryPrefix === true ? "?" : ""; + if (options.charsetSentinel) { + if (options.charset === "iso-8859-1") { + prefix += "utf8=%26%2310003%3B&"; + } else { + prefix += "utf8=%E2%9C%93&"; } + } + return joined.length > 0 ? prefix + joined : ""; +} + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/resources/apps/installations/installations.mjs +var BaseInstallations = /* @__PURE__ */ (() => { + class BaseInstallations4 extends APIResource2 { /** - * Unsubscribe from a resource + * Enables an authenticated GitHub App to find an installation's information using + * the installation id. * - * @example - * ```ts - * const apiEntitiesMergeRequest = - * await client.projects.mergeRequests.unsubscribe( - * 'subscribable_id', - * { id: 'id' }, - * ); - * ``` - */ - unsubscribe(subscribableID, params, options) { - const { id } = params; - return this._client.post(path2`/projects/${id}/merge_requests/${subscribableID}/unsubscribe`, options); - } - /** - * Accept and merge changes submitted with the merge request using this API. + * You must use a + * [JWT](https://docs.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) + * to access this endpoint. * * @example * ```ts - * const apiEntitiesMergeRequest = - * await client.projects.mergeRequests.updateMerge(0, { - * id: 'string', - * }); + * const installation = + * await client.apps.installations.retrieve(0); * ``` */ - updateMerge(mergeRequestIid, params, options) { - const { id, ...body } = params; - return this._client.put(path2`/projects/${id}/merge_requests/${mergeRequestIid}/merge`, { - body, - ...options - }); + retrieve(installationID, options) { + return this._client.get(path2`/app/installations/${installationID}`, options); } /** - * Automatically rebase the `source_branch` of the merge request against its - * `target_branch`. This feature was added in GitLab 11.6 + * The permissions the installation has are included under the `permissions` key. * - * @example - * ```ts - * await client.projects.mergeRequests.updateRebase(0, { - * id: 'string', - * }); - * ``` - */ - updateRebase(mergeRequestIid, params, options) { - const { id, ...body } = params; - return this._client.put(path2`/projects/${id}/merge_requests/${mergeRequestIid}/rebase`, { - body, - ...options, - headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) - }); - } - /** - * Clear all approvals of merge request. This feature was added in GitLab 15.4 + * You must use a + * [JWT](https://docs.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) + * to access this endpoint. * * @example * ```ts - * await client.projects.mergeRequests.updateResetApprovals( - * 0, - * { id: 'id' }, - * ); + * // Automatically fetches more pages as needed. + * for await (const installation of client.apps.installations.list()) { + * // ... + * } * ``` */ - updateResetApprovals(mergeRequestIid, params, options) { - const { id } = params; - return this._client.put(path2`/projects/${id}/merge_requests/${mergeRequestIid}/reset_approvals`, { - ...options, - headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + list(query = {}, options) { + return this._client.getAPIList("/app/installations", NumberedPage, { + query, + ...options }); } - } - BaseMergeRequests3._key = Object.freeze([ - "projects", - "mergeRequests" - ]); - return BaseMergeRequests3; -})(); - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/shims.mjs -function getDefaultFetch2() { - if (typeof fetch !== "undefined") { - return fetch; - } - throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new GitLab({ fetch })` or polyfill the global, `globalThis.fetch = fetch`"); -} -function makeReadableStream2(...args) { - const ReadableStream = globalThis.ReadableStream; - if (typeof ReadableStream === "undefined") { - throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`"); - } - return new ReadableStream(...args); -} -function ReadableStreamFrom2(iterable) { - let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); - return makeReadableStream2({ - start() { - }, - async pull(controller) { - const { done, value } = await iter.next(); - if (done) { - controller.close(); - } else { - controller.enqueue(value); - } - }, - async cancel() { - await iter.return?.(); - } - }); -} -async function CancelReadableStream2(stream) { - if (stream === null || typeof stream !== "object") - return; - if (stream[Symbol.asyncIterator]) { - await stream[Symbol.asyncIterator]().return?.(); - return; - } - const reader = stream.getReader(); - const cancelPromise = reader.cancel(); - reader.releaseLock(); - await cancelPromise; -} - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/uploads.mjs -var checkFileSupport2 = () => { - if (typeof File === "undefined") { - const { process: process7 } = globalThis; - const isOldNode = typeof process7?.versions?.node === "string" && parseInt(process7.versions.node.split(".")) < 20; - throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : "")); - } -}; -function makeFile2(fileBits, fileName, options) { - checkFileSupport2(); - return new File(fileBits, fileName ?? "unknown_file", options); -} -function getName2(value) { - return (typeof value === "object" && value !== null && ("name" in value && value.name && String(value.name) || "url" in value && value.url && String(value.url) || "filename" in value && value.filename && String(value.filename) || "path" in value && value.path && String(value.path)) || "").split(/[\\/]/).pop() || void 0; -} -var isAsyncIterable2 = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function"; -var multipartFormRequestOptions = async (opts, fetch2) => { - return { ...opts, body: await createForm(opts.body, fetch2) }; -}; -var supportsFormDataMap = /* @__PURE__ */ new WeakMap(); -function supportsFormData(fetchObject) { - const fetch2 = typeof fetchObject === "function" ? fetchObject : fetchObject.fetch; - const cached = supportsFormDataMap.get(fetch2); - if (cached) - return cached; - const promise = (async () => { - try { - const FetchResponse = "Response" in fetch2 ? fetch2.Response : (await fetch2("data:,")).constructor; - const data = new FormData(); - if (data.toString() === await new FetchResponse(data).text()) { - return false; - } - return true; - } catch { - return true; - } - })(); - supportsFormDataMap.set(fetch2, promise); - return promise; -} -var createForm = async (body, fetch2) => { - if (!await supportsFormData(fetch2)) { - throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class."); - } - const form = new FormData(); - await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value))); - return form; -}; -var isNamedBlob = (value) => value instanceof Blob && "name" in value; -var addFormValue = async (form, key, value) => { - if (value === void 0) - return; - if (value == null) { - throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`); - } - if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { - form.append(key, String(value)); - } else if (value instanceof Response) { - form.append(key, makeFile2([await value.blob()], getName2(value))); - } else if (isAsyncIterable2(value)) { - form.append(key, makeFile2([await new Response(ReadableStreamFrom2(value)).blob()], getName2(value))); - } else if (isNamedBlob(value)) { - form.append(key, value, getName2(value)); - } else if (Array.isArray(value)) { - await Promise.all(value.map((entry) => addFormValue(form, key + "[]", entry))); - } else if (typeof value === "object") { - await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop))); - } else { - throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); - } -}; - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/resources/projects/repository/commits/commits.mjs -var BaseCommits3 = /* @__PURE__ */ (() => { - class BaseCommits4 extends APIResource2 { /** - * This feature was introduced in GitLab 8.13 + * Uninstalls a GitHub App on a user, organization, or enterprise account. If you + * prefer to temporarily suspend an app's access to your account's resources, then + * we recommend the + * "[Suspend an app installation](https://docs.github.com/rest/apps/apps#suspend-an-app-installation)" + * endpoint. + * + * You must use a + * [JWT](https://docs.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) + * to access this endpoint. * * @example * ```ts - * const apiEntitiesCommitDetail = - * await client.projects.repository.commits.create( - * 'string', - * { file: fs.createReadStream('path/to/file') }, - * ); + * await client.apps.installations.delete(0); * ``` */ - create(id, body, options) { - return this._client.post(path2`/projects/${id}/repository/commits`, multipartFormRequestOptions({ body, ...options }, this._client)); + delete(installationID, options) { + return this._client.delete(path2`/app/installations/${installationID}`, { + ...options, + headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + }); } /** - * Get a specific commit of a project + * Creates an installation access token that enables a GitHub App to make + * authenticated API requests for the app's installation on an organization or + * individual account. Installation tokens expire one hour from the time you create + * them. Using an expired token produces a status code of `401 - Unauthorized`, and + * requires creating a new installation token. By default the installation token + * has access to all repositories that the installation can access. + * + * Optionally, you can use the `repositories` or `repository_ids` body parameters + * to specify individual repositories that the installation access token can + * access. If you don't use `repositories` or `repository_ids` to grant access to + * specific repositories, the installation access token will have access to all + * repositories that the installation was granted access to. The installation + * access token cannot be granted access to repositories that the installation was + * not granted access to. Up to 500 repositories can be listed in this manner. + * + * Optionally, use the `permissions` body parameter to specify the permissions that + * the installation access token should have. If `permissions` is not specified, + * the installation access token will have all of the permissions that were granted + * to the app. The installation access token cannot be granted permissions that the + * app was not granted. + * + * You must use a + * [JWT](https://docs.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) + * to access this endpoint. * * @example * ```ts - * const apiEntitiesCommitDetail = - * await client.projects.repository.commits.retrieve('sha', { - * id: 'string', + * const response = + * await client.apps.installations.createAccessToken(0, { + * permissions: { issues: 'write', contents: 'read' }, + * repositories: ['Hello-World'], * }); * ``` */ - retrieve(sha, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/repository/commits/${sha}`, { query, ...options }); + createAccessToken(installationID, body = {}, options) { + return this._client.post(path2`/app/installations/${installationID}/access_tokens`, { body, ...options }); } + } + BaseInstallations4._key = Object.freeze([ + "apps", + "installations" + ]); + return BaseInstallations4; +})(); + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/resources/orgs/orgs.mjs +var BaseOrgs = /* @__PURE__ */ (() => { + class BaseOrgs3 extends APIResource2 { /** - * Get a project repository commits + * Gets information about an organization. + * + * When the value of `two_factor_requirement_enabled` is `true`, the organization + * requires all members, billing managers, outside collaborators, guest + * collaborators, repository collaborators, or everyone with access to any + * repository within the organization to enable + * [two-factor authentication](https://docs.github.com/articles/securing-your-account-with-two-factor-authentication-2fa/). + * + * To see the full details about an organization, the authenticated user must be an + * organization owner. + * + * OAuth app tokens and personal access tokens (classic) need the `admin:org` scope + * to see the full details about an organization. + * + * To see information about an organization's GitHub plan, GitHub Apps need the + * `Organization plan` permission. * * @example * ```ts - * const apiEntitiesCommits = - * await client.projects.repository.commits.list('string'); + * const org = await client.orgs.retrieve('org'); * ``` */ - list(id, query = {}, options) { - return this._client.get(path2`/projects/${id}/repository/commits`, { query, ...options }); + retrieve(org, options) { + return this._client.get(path2`/orgs/${org}`, options); } /** - * Authorize commits upload + * > [!WARNING] > **Closing down notice:** GitHub will replace and discontinue + * > `members_allowed_repository_creation_type` in favor of more granular + * > permissions. The new input parameters are + * > `members_can_create_public_repositories`, + * > `members_can_create_private_repositories` for all organizations and + * > `members_can_create_internal_repositories` for organizations associated with + * > an enterprise account using GitHub Enterprise Cloud or GitHub Enterprise + * > Server 2.20+. For more information, see the + * > [blog post](https://developer.github.com/changes/2019-12-03-internal-visibility-changes). + * + * > [!WARNING] > **Closing down notice:** Code security product enablement for new + * > repositories through the organization API is closing down. Please use + * > [code security configurations](https://docs.github.com/rest/code-security/configurations#set-a-code-security-configuration-as-a-default-for-an-organization) + * > to set defaults instead. For more information on setting a default security + * > configuration, see the + * > [changelog](https://github.blog/changelog/2024-07-09-sunsetting-security-settings-defaults-parameters-in-the-organizations-rest-api/). + * + * Updates the organization's profile and member privileges. + * + * The authenticated user must be an organization owner to use this endpoint. + * + * OAuth app tokens and personal access tokens (classic) need the `admin:org` or + * `repo` scope to use this endpoint. * * @example * ```ts - * await client.projects.repository.commits.authorize( - * 'string', - * ); + * const org = await client.orgs.update('org', { + * billing_email: 'mona@github.com', + * company: 'GitHub', + * default_repository_permission: 'read', + * description: 'GitHub, the company.', + * email: 'mona@github.com', + * location: 'San Francisco', + * members_allowed_repository_creation_type: 'all', + * members_can_create_repositories: true, + * name: 'github', + * twitter_username: 'github', + * }); * ``` */ - authorize(id, options) { - return this._client.post(path2`/projects/${id}/repository/commits/authorize`, { - ...options, - headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) - }); + update(org, body = {}, options) { + return this._client.patch(path2`/orgs/${org}`, { body, ...options }); } /** - * This feature was introduced in GitLab 8.15 + * Deletes an organization and all its repositories. + * + * The organization login will be unavailable for 90 days after deletion. + * + * Please review the Terms of Service regarding account deletion before using this + * endpoint: + * + * https://docs.github.com/site-policy/github-terms/github-terms-of-service * * @example * ```ts - * const apiEntitiesCommit = - * await client.projects.repository.commits.cherryPick( - * 'sha', - * { id: 'string', branch: 'master' }, - * ); + * const org = await client.orgs.delete('org'); * ``` */ - cherryPick(sha, params, options) { - const { id, ...body } = params; - return this._client.post(path2`/projects/${id}/repository/commits/${sha}/cherry_pick`, { - body, - ...options - }); + delete(org, options) { + return this._client.delete(path2`/orgs/${org}`, options); } /** - * Get the diff for a specific commit of a project + * List a collection of artifact attestations with a given subject digest that are + * associated with repositories owned by an organization. + * + * The collection of attestations returned by this endpoint is filtered according + * to the authenticated user's permissions; if the authenticated user cannot read a + * repository, the attestations associated with that repository will not be + * included in the response. In addition, when using a fine-grained access token + * the `attestations:read` permission is required. + * + * **Please note:** in order to offer meaningful security benefits, an + * attestation's signature and timestamps **must** be cryptographically verified, + * and the identity of the attestation signer **must** be validated. Attestations + * can be verified using the + * [GitHub CLI `attestation verify` command](https://cli.github.com/manual/gh_attestation_verify). + * For more information, see + * [our guide on how to use artifact attestations to establish a build's provenance](https://docs.github.com/actions/security-guides/using-artifact-attestations-to-establish-provenance-for-builds). * * @example * ```ts - * const apiEntitiesDiffs = - * await client.projects.repository.commits.retrieveDiff( - * 'sha', - * { id: 'string' }, - * ); + * const response = await client.orgs.listAttestations( + * 'subject_digest', + * { org: 'org' }, + * ); * ``` */ - retrieveDiff(sha, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/repository/commits/${sha}/diff`, { query, ...options }); + listAttestations(subjectDigest, params, options) { + const { org, ...query } = params; + return this._client.get(path2`/orgs/${org}/attestations/${subjectDigest}`, { query, ...options }); } /** - * Get Merge Requests associated with a commit + * > [!NOTE] This API is not built to serve real-time use cases. Depending on the + * > time of day, event latency can be anywhere from 30s to 6h. * * @example * ```ts - * const apiEntitiesMergeRequestBasic = - * await client.projects.repository.commits.retrieveMergeRequests( - * 'sha', - * { id: 'string' }, - * ); + * // Automatically fetches more pages as needed. + * for await (const orgListEventsResponse of client.orgs.listEvents( + * 'org', + * )) { + * // ... + * } * ``` */ - retrieveMergeRequests(sha, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/repository/commits/${sha}/merge_requests`, { + listEvents(org, query = {}, options) { + return this._client.getAPIList(path2`/orgs/${org}/events`, NumberedPage, { query, ...options }); } /** - * This feature was introduced in GitLab 10.6 + * The return hash contains `failed_at` and `failed_reason` fields which represent + * the time at which the invitation failed and the reason for the failure. * * @example * ```ts - * const response = - * await client.projects.repository.commits.retrieveRefs( - * 'sha', - * { id: 'string' }, - * ); + * // Automatically fetches more pages as needed. + * for await (const orgListFailedInvitationsResponse of client.orgs.listFailedInvitations( + * 'org', + * )) { + * // ... + * } * ``` */ - retrieveRefs(sha, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/repository/commits/${sha}/refs`, { query, ...options }); + listFailedInvitations(org, query = {}, options) { + return this._client.getAPIList(path2`/orgs/${org}/failed_invitations`, NumberedPage, { query, ...options }); } /** - * Get the sequence count of a commit SHA + * Lists all GitHub Apps in an organization. The installation count includes all + * GitHub Apps installed on repositories in the organization. + * + * The authenticated user must be an organization owner to use this endpoint. + * + * OAuth app tokens and personal access tokens (classic) need the `admin:read` + * scope to use this endpoint. * * @example * ```ts - * const response = - * await client.projects.repository.commits.retrieveSequence( - * 'sha', - * { id: 'string' }, - * ); + * const response = await client.orgs.listInstallations('org'); * ``` */ - retrieveSequence(sha, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/repository/commits/${sha}/sequence`, { query, ...options }); + listInstallations(org, query = {}, options) { + return this._client.get(path2`/orgs/${org}/installations`, { query, ...options }); } /** - * Get a commit's signature + * List issues in an organization assigned to the authenticated user. + * + * > [!NOTE] GitHub's REST API considers every pull request an issue, but not every + * > issue is a pull request. For this reason, "Issues" endpoints may return both + * > issues and pull requests in the response. You can identify pull requests by + * > the `pull_request` key. Be aware that the `id` of a pull request returned from + * > "Issues" endpoints will be an _issue id_. To find out the pull request id, use + * > the + * > "[List pull requests](https://docs.github.com/rest/pulls/pulls#list-pull-requests)" + * > endpoint. + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response + * will include `body`. This is the default if you do not pass any specific media + * type. + * - **`application/vnd.github.text+json`**: Returns a text only representation of + * the markdown body. Response will include `body_text`. + * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's + * markdown. Response will include `body_html`. + * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML + * representations. Response will include `body`, `body_text`, and `body_html`. * * @example * ```ts - * const response = - * await client.projects.repository.commits.retrieveSignature( - * 'sha', - * { id: 'string' }, - * ); + * // Automatically fetches more pages as needed. + * for await (const issue of client.orgs.listIssues('org')) { + * // ... + * } * ``` */ - retrieveSignature(sha, params, options) { - const { id } = params; - return this._client.get(path2`/projects/${id}/repository/commits/${sha}/signature`, options); + listIssues(org, query = {}, options) { + return this._client.getAPIList(path2`/orgs/${org}/issues`, NumberedPage, { + query, + ...options + }); } /** - * Get a commit's statuses + * Lists repository security advisories for an organization. + * + * The authenticated user must be an owner or security manager for the organization + * to use this endpoint. + * + * OAuth app tokens and personal access tokens (classic) need the `repo` or + * `repository_advisories:write` scope to use this endpoint. * * @example * ```ts - * const apiEntitiesCommitStatus = - * await client.projects.repository.commits.retrieveStatuses( - * '18f3e63d05582537db6d183d9d557be09e1f90c8', - * { id: 'string' }, - * ); + * const response = await client.orgs.listSecurityAdvisories( + * 'org', + * ); * ``` */ - retrieveStatuses(sha, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/repository/commits/${sha}/statuses`, { query, ...options }); + listSecurityAdvisories(org, query = {}, options) { + return this._client.get(path2`/orgs/${org}/security-advisories`, { query, ...options }); } /** - * This feature was introduced in GitLab 11.5 + * Enables an authenticated GitHub App to find the organization's installation + * information. + * + * You must use a + * [JWT](https://docs.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) + * to access this endpoint. * * @example * ```ts - * const apiEntitiesCommit = - * await client.projects.repository.commits.revert('sha', { - * id: 'string', - * branch: 'master', - * }); + * const installation = await client.orgs.retrieveInstallation( + * 'org', + * ); * ``` */ - revert(sha, params, options) { - const { id, ...body } = params; - return this._client.post(path2`/projects/${id}/repository/commits/${sha}/revert`, { body, ...options }); + retrieveInstallation(org, options) { + return this._client.get(path2`/orgs/${org}/installation`, options); } } - BaseCommits4._key = Object.freeze([ - "projects", - "repository", - "commits" - ]); - return BaseCommits4; + BaseOrgs3._key = Object.freeze(["orgs"]); + return BaseOrgs3; })(); -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/tslib.mjs -function __classPrivateFieldSet2(receiver, state, value, kind, f) { - if (kind === "m") - throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) - throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) - throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; -} -function __classPrivateFieldGet2(receiver, state, kind, f) { - if (kind === "a" && !f) - throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) - throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -} - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/utils/uuid.mjs -var uuid42 = function() { - const { crypto: crypto2 } = globalThis; - if (crypto2?.randomUUID) { - uuid42 = crypto2.randomUUID.bind(crypto2); - return crypto2.randomUUID(); - } - const u8 = new Uint8Array(1); - const randomByte = crypto2 ? () => crypto2.getRandomValues(u8)[0] : () => Math.random() * 255 & 255; - return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16)); -}; - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/utils/sleep.mjs -var sleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/version.mjs -var VERSION2 = "0.3.0"; - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/detect-platform.mjs -function getDetectedPlatform2() { - if (typeof Deno !== "undefined" && Deno.build != null) { - return "deno"; - } - if (typeof EdgeRuntime !== "undefined") { - return "edge"; - } - if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") { - return "node"; - } - return "unknown"; -} -var getPlatformProperties2 = () => { - const detectedPlatform = getDetectedPlatform2(); - if (detectedPlatform === "deno") { - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION2, - "X-Stainless-OS": normalizePlatform2(Deno.build.os), - "X-Stainless-Arch": normalizeArch2(Deno.build.arch), - "X-Stainless-Runtime": "deno", - "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown" - }; - } - if (typeof EdgeRuntime !== "undefined") { - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION2, - "X-Stainless-OS": "Unknown", - "X-Stainless-Arch": `other:${EdgeRuntime}`, - "X-Stainless-Runtime": "edge", - "X-Stainless-Runtime-Version": globalThis.process.version - }; - } - if (detectedPlatform === "node") { - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION2, - "X-Stainless-OS": normalizePlatform2(globalThis.process.platform ?? "unknown"), - "X-Stainless-Arch": normalizeArch2(globalThis.process.arch ?? "unknown"), - "X-Stainless-Runtime": "node", - "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown" - }; - } - const browserInfo = getBrowserInfo2(); - if (browserInfo) { - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION2, - "X-Stainless-OS": "Unknown", - "X-Stainless-Arch": "unknown", - "X-Stainless-Runtime": `browser:${browserInfo.browser}`, - "X-Stainless-Runtime-Version": browserInfo.version - }; - } - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION2, - "X-Stainless-OS": "Unknown", - "X-Stainless-Arch": "unknown", - "X-Stainless-Runtime": "unknown", - "X-Stainless-Runtime-Version": "unknown" - }; -}; -function getBrowserInfo2() { - if (typeof navigator === "undefined" || !navigator) { - return null; - } - const browserPatterns = [ - { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ } - ]; - for (const { key, pattern } of browserPatterns) { - const match = pattern.exec(navigator.userAgent); - if (match) { - const major = match[1] || 0; - const minor = match[2] || 0; - const patch = match[3] || 0; - return { browser: key, version: `${major}.${minor}.${patch}` }; +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/resources/search.mjs +var BaseSearch = /* @__PURE__ */ (() => { + class BaseSearch6 extends APIResource2 { + /** + * Searches for query terms inside of a file. This method returns up to 100 results + * [per page](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api). + * + * When searching for code, you can get text match metadata for the file + * **content** and file **path** fields when you pass the `text-match` media type. + * For more details about how to receive highlighted search results, see + * [Text match metadata](https://docs.github.com/rest/search/search#text-match-metadata). + * + * For example, if you want to find the definition of the `addClass` function + * inside [jQuery](https://github.com/jquery/jquery) repository, your query would + * look something like this: + * + * `q=addClass+in:file+language:js+repo:jquery/jquery` + * + * This query searches for the keyword `addClass` within a file's contents. The + * query limits the search to files where the language is JavaScript in the + * `jquery/jquery` repository. + * + * Considerations for code search: + * + * Due to the complexity of searching code, there are a few restrictions on how + * searches are performed: + * + * - Only the _default branch_ is considered. In most cases, this will be the + * `master` branch. + * - Only files smaller than 384 KB are searchable. + * - You must always include at least one search term when searching source code. + * For example, searching for + * [`language:go`](https://github.com/search?utf8=%E2%9C%93&q=language%3Ago&type=Code) + * is not valid, while + * [`amazing language:go`](https://github.com/search?utf8=%E2%9C%93&q=amazing+language%3Ago&type=Code) + * is. + * + * This endpoint requires you to authenticate and limits you to 10 requests per + * minute. + */ + codeSearch(query, options) { + return this._client.get("/search/code", { query, ...options }); + } + /** + * Find commits via various criteria on the default branch (usually `main`). This + * method returns up to 100 results + * [per page](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api). + * + * When searching for commits, you can get text match metadata for the **message** + * field when you provide the `text-match` media type. For more details about how + * to receive highlighted search results, see + * [Text match metadata](https://docs.github.com/rest/search/search#text-match-metadata). + * + * For example, if you want to find commits related to CSS in the + * [octocat/Spoon-Knife](https://github.com/octocat/Spoon-Knife) repository. Your + * query would look something like this: + * + * `q=repo:octocat/Spoon-Knife+css` + */ + commitSearch(query, options) { + return this._client.get("/search/commits", { query, ...options }); + } + /** + * > [!WARNING] > **Notice:** Search for issues and pull requests will be + * > overridden by advanced search on November 4, 2025. You can read more about + * > this change on + * > [the GitHub blog](https://github.blog/changelog/2025-03-06-github-issues-projects-api-support-for-issues-advanced-search-and-more/). + * + * @deprecated + */ + issueSearch(query, options) { + return this._client.get("/search/issues", { query, ...options }); + } + /** + * Find labels in a repository with names or descriptions that match search + * keywords. Returns up to 100 results + * [per page](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api). + * + * When searching for labels, you can get text match metadata for the label + * **name** and **description** fields when you pass the `text-match` media type. + * For more details about how to receive highlighted search results, see + * [Text match metadata](https://docs.github.com/rest/search/search#text-match-metadata). + * + * For example, if you want to find labels in the `linguist` repository that match + * `bug`, `defect`, or `enhancement`. Your query might look like this: + * + * `q=bug+defect+enhancement&repository_id=64778136` + * + * The labels that best match the query appear first in the search results. + */ + labelSearch(query, options) { + return this._client.get("/search/labels", { query, ...options }); + } + /** + * Find repositories via various criteria. This method returns up to 100 results + * [per page](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api). + * + * When searching for repositories, you can get text match metadata for the + * **name** and **description** fields when you pass the `text-match` media type. + * For more details about how to receive highlighted search results, see + * [Text match metadata](https://docs.github.com/rest/search/search#text-match-metadata). + * + * For example, if you want to search for popular Tetris repositories written in + * assembly code, your query might look like this: + * + * `q=tetris+language:assembly&sort=stars&order=desc` + * + * This query searches for repositories with the word `tetris` in the name, the + * description, or the README. The results are limited to repositories where the + * primary language is assembly. The results are sorted by stars in descending + * order, so that the most popular repositories appear first in the search results. + */ + repositorySearch(query, options) { + return this._client.get("/search/repositories", { query, ...options }); + } + /** + * Find topics via various criteria. Results are sorted by best match. This method + * returns up to 100 results + * [per page](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api). + * See "[Searching topics](https://docs.github.com/articles/searching-topics/)" for + * a detailed list of qualifiers. + * + * When searching for topics, you can get text match metadata for the topic's + * **short_description**, **description**, **name**, or **display_name** field when + * you pass the `text-match` media type. For more details about how to receive + * highlighted search results, see + * [Text match metadata](https://docs.github.com/rest/search/search#text-match-metadata). + * + * For example, if you want to search for topics related to Ruby that are featured + * on https://github.com/topics. Your query might look like this: + * + * `q=ruby+is:featured` + * + * This query searches for topics with the keyword `ruby` and limits the results to + * find only topics that are featured. The topics that are the best match for the + * query appear first in the search results. + */ + topicSearch(query, options) { + return this._client.get("/search/topics", { query, ...options }); + } + /** + * Find users via various criteria. This method returns up to 100 results + * [per page](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api). + * + * When searching for users, you can get text match metadata for the issue + * **login**, public **email**, and **name** fields when you pass the `text-match` + * media type. For more details about highlighting search results, see + * [Text match metadata](https://docs.github.com/rest/search/search#text-match-metadata). + * For more details about how to receive highlighted search results, see + * [Text match metadata](https://docs.github.com/rest/search/search#text-match-metadata). + * + * For example, if you're looking for a list of popular users, you might try this + * query: + * + * `q=tom+repos:%3E42+followers:%3E1000` + * + * This query searches for users with the name `tom`. The results are restricted to + * users with more than 42 repositories and over 1,000 followers. + * + * This endpoint does not accept authentication and will only include publicly + * visible users. As an alternative, you can use the GraphQL API. The GraphQL API + * requires authentication and will return private users, including Enterprise + * Managed Users (EMUs), that you are authorized to view. For more information, see + * "[GraphQL Queries](https://docs.github.com/graphql/reference/queries#search)." + */ + userSearch(query, options) { + return this._client.get("/search/users", { query, ...options }); } } - return null; -} -var normalizeArch2 = (arch) => { - if (arch === "x32") - return "x32"; - if (arch === "x86_64" || arch === "x64") - return "x64"; - if (arch === "arm") - return "arm"; - if (arch === "aarch64" || arch === "arm64") - return "arm64"; - if (arch) - return `other:${arch}`; - return "unknown"; -}; -var normalizePlatform2 = (platform) => { - platform = platform.toLowerCase(); - if (platform.includes("ios")) - return "iOS"; - if (platform === "android") - return "Android"; - if (platform === "darwin") - return "MacOS"; - if (platform === "win32") - return "Windows"; - if (platform === "freebsd") - return "FreeBSD"; - if (platform === "openbsd") - return "OpenBSD"; - if (platform === "linux") - return "Linux"; - if (platform) - return `Other:${platform}`; - return "Unknown"; -}; -var _platformHeaders2; -var getPlatformHeaders2 = () => { - return _platformHeaders2 ?? (_platformHeaders2 = getPlatformProperties2()); -}; - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/request-options.mjs -var FallbackEncoder2 = ({ headers, body }) => { - return { - bodyHeaders: { - "content-type": "application/json" - }, - body: JSON.stringify(body) - }; + BaseSearch6._key = Object.freeze(["search"]); + return BaseSearch6; +})(); +var Search = class extends BaseSearch { }; -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/qs/formats.mjs -var default_format2 = "RFC3986"; -var default_formatter2 = (v) => String(v); -var formatters2 = { - RFC1738: (v) => String(v).replace(/%20/g, "+"), - RFC3986: default_formatter2 -}; -var RFC17382 = "RFC1738"; +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/lib/secrets.mjs +var import_libsodium_wrappers = __toESM(require_libsodium_wrappers(), 1); -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/qs/utils.mjs -var has2 = (obj, key) => (has2 = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has2(obj, key)); -var hex_table2 = /* @__PURE__ */ (() => { - const array = []; - for (let i = 0; i < 256; ++i) { - array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase()); - } - return array; -})(); -var limit2 = 1024; -var encode2 = (str, _defaultEncoder, charset, _kind, format) => { - if (str.length === 0) { - return str; - } - let string = str; - if (typeof str === "symbol") { - string = Symbol.prototype.toString.call(str); - } else if (typeof str !== "string") { - string = String(str); - } - if (charset === "iso-8859-1") { - return escape(string).replace(/%u[0-9a-f]{4}/gi, function($0) { - return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; - }); - } - let out = ""; - for (let j = 0; j < string.length; j += limit2) { - const segment = string.length >= limit2 ? string.slice(j, j + limit2) : string; - const arr = []; - for (let i = 0; i < segment.length; ++i) { - let c = segment.charCodeAt(i); - if (c === 45 || // - - c === 46 || // . - c === 95 || // _ - c === 126 || // ~ - c >= 48 && c <= 57 || // 0-9 - c >= 65 && c <= 90 || // a-z - c >= 97 && c <= 122 || // A-Z - format === RFC17382 && (c === 40 || c === 41)) { - arr[arr.length] = segment.charAt(i); - continue; - } - if (c < 128) { - arr[arr.length] = hex_table2[c]; - continue; - } - if (c < 2048) { - arr[arr.length] = hex_table2[192 | c >> 6] + hex_table2[128 | c & 63]; - continue; - } - if (c < 55296 || c >= 57344) { - arr[arr.length] = hex_table2[224 | c >> 12] + hex_table2[128 | c >> 6 & 63] + hex_table2[128 | c & 63]; - continue; - } - i += 1; - c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023); - arr[arr.length] = hex_table2[240 | c >> 18] + hex_table2[128 | c >> 12 & 63] + hex_table2[128 | c >> 6 & 63] + hex_table2[128 | c & 63]; +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/resources/repos/repos.mjs +var BaseRepos3 = /* @__PURE__ */ (() => { + class BaseRepos6 extends APIResource2 { + constructor() { + super(...arguments); + this._client_search = new Search(this._client); + this.search = { + codeSearch: (params, options) => { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params; + query.q = `repo:${owner}/${repo} ${query.q}`; + return this._client_search.codeSearch(query, options); + }, + commitSearch: (params, options) => { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params; + query.q = `repo:${owner}/${repo} ${query.q}`; + return this._client_search.commitSearch(query, options); + }, + issueSearch: (params, options) => { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params; + query.q = `repo:${owner}/${repo} ${query.q}`; + return this._client_search.issueSearch(query, options); + }, + labelSearch: (params, options) => { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params; + query.q = `repo:${owner}/${repo} ${query.q}`; + return this._client_search.labelSearch(query, options); + } + }; + } + /** + * Creates a new repository for the authenticated user. + * + * OAuth app tokens and personal access tokens (classic) need the `public_repo` or + * `repo` scope to create a public repository, and `repo` scope to create a private + * repository. + * + * @example + * ```ts + * const fullRepository = await client.repos.create({ + * name: 'Hello-World', + * description: 'This is your first repo!', + * homepage: 'https://github.com', + * is_template: true, + * }); + * ``` + */ + create(body, options) { + return this._client.post("/user/repos", { body, ...options }); } - out += arr.join(""); - } - return out; -}; -function is_buffer2(obj) { - if (!obj || typeof obj !== "object") { - return false; - } - return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); -} -function maybe_map2(val, fn) { - if (isArray2(val)) { - const mapped = []; - for (let i = 0; i < val.length; i += 1) { - mapped.push(fn(val[i])); + /** + * The `parent` and `source` objects are present when the repository is a fork. + * `parent` is the repository this repository was forked from, `source` is the + * ultimate source for the network. + * + * > [!NOTE] + * > + * > - In order to see the `security_and_analysis` block for a repository you must + * > have admin permissions for the repository or be an owner or security manager + * > for the organization that owns the repository. For more information, see + * > "[Managing security managers in your organization](https://docs.github.com/organizations/managing-peoples-access-to-your-organization-with-roles/managing-security-managers-in-your-organization)." + * > - To view merge-related settings, you must have the `contents:read` and + * > `contents:write` permissions. + * + * @example + * ```ts + * const fullRepository = await client.repos.retrieve({ + * owner: 'owner', + * repo: 'repo', + * }); + * ``` + */ + retrieve(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}`, options); } - return mapped; - } - return fn(val); -} - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/qs/stringify.mjs -var array_prefix_generators2 = { - brackets(prefix) { - return String(prefix) + "[]"; - }, - comma: "comma", - indices(prefix, key) { - return String(prefix) + "[" + key + "]"; - }, - repeat(prefix) { - return String(prefix); - } -}; -var push_to_array2 = function(arr, value_or_array) { - Array.prototype.push.apply(arr, isArray2(value_or_array) ? value_or_array : [value_or_array]); -}; -var toISOString2; -var defaults2 = { - addQueryPrefix: false, - allowDots: false, - allowEmptyArrays: false, - arrayFormat: "indices", - charset: "utf-8", - charsetSentinel: false, - delimiter: "&", - encode: true, - encodeDotInKeys: false, - encoder: encode2, - encodeValuesOnly: false, - format: default_format2, - formatter: default_formatter2, - /** @deprecated */ - indices: false, - serializeDate(date) { - return (toISOString2 ?? (toISOString2 = Function.prototype.call.bind(Date.prototype.toISOString)))(date); - }, - skipNulls: false, - strictNullHandling: false -}; -function is_non_nullish_primitive2(v) { - return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint"; -} -var sentinel2 = {}; -function inner_stringify2(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { - let obj = object; - let tmp_sc = sideChannel; - let step = 0; - let find_flag = false; - while ((tmp_sc = tmp_sc.get(sentinel2)) !== void 0 && !find_flag) { - const pos = tmp_sc.get(object); - step += 1; - if (typeof pos !== "undefined") { - if (pos === step) { - throw new RangeError("Cyclic object value"); - } else { - find_flag = true; - } + /** + * **Note**: To edit a repository's topics, use the + * [Replace all repository topics](https://docs.github.com/rest/repos/repos#replace-all-repository-topics) + * endpoint. + * + * @example + * ```ts + * const fullRepository = await client.repos.update({ + * owner: 'owner', + * repo: 'repo', + * description: 'This is your first repository', + * has_issues: true, + * has_projects: true, + * has_wiki: true, + * homepage: 'https://github.com', + * name: 'Hello-World', + * private: true, + * }); + * ``` + */ + update(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...body } = params ?? {}; + return this._client.patch(path2`/repos/${owner}/${repo}`, { body, ...options }); } - if (typeof tmp_sc.get(sentinel2) === "undefined") { - step = 0; + /** + * Deleting a repository requires admin access. + * + * If an organization owner has configured the organization to prevent members from + * deleting organization-owned repositories, you will get a `403 Forbidden` + * response. + * + * OAuth app tokens and personal access tokens (classic) need the `delete_repo` + * scope to use this endpoint. + * + * @example + * ```ts + * await client.repos.delete({ owner: 'owner', repo: 'repo' }); + * ``` + */ + delete(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; + return this._client.delete(path2`/repos/${owner}/${repo}`, { + ...options, + headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + }); + } + /** + * Whether the authenticated user has starred the repository. + * + * @example + * ```ts + * await client.repos.checkStarred({ + * owner: 'owner', + * repo: 'repo', + * }); + * ``` + */ + checkStarred(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; + return this._client.get(path2`/user/starred/${owner}/${repo}`, { + ...options, + headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + }); + } + /** + * Compares two commits against one another. You can compare refs (branches or + * tags) and commit SHAs in the same repository, or you can compare refs and commit + * SHAs that exist in different repositories within the same repository network, + * including fork branches. For more information about how to view a repository's + * network, see + * "[Understanding connections between repositories](https://docs.github.com/repositories/viewing-activity-and-data-for-your-repository/understanding-connections-between-repositories)." + * + * This endpoint is equivalent to running the `git log BASE..HEAD` command, but it + * returns commits in a different order. The `git log BASE..HEAD` command returns + * commits in reverse chronological order, whereas the API returns commits in + * chronological order. + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.diff`**: Returns the diff of the commit. + * - **`application/vnd.github.patch`**: Returns the patch of the commit. Diffs + * with binary data will have no `patch` property. + * + * The API response includes details about the files that were changed between the + * two commits. This includes the status of the change (if a file was added, + * removed, modified, or renamed), and details of the change itself. For example, + * files with a `renamed` status have a `previous_filename` field showing the + * previous filename of the file, and files with a `modified` status have a `patch` + * field showing the changes made to the file. + * + * When calling this endpoint without any paging parameter (`per_page` or `page`), + * the returned list is limited to 250 commits, and the last commit in the list is + * the most recent of the entire comparison. + * + * **Working with large comparisons** + * + * To process a response with a large number of commits, use a query parameter + * (`per_page` or `page`) to paginate the results. When using pagination: + * + * - The list of changed files is only shown on the first page of results, and it + * includes up to 300 changed files for the entire comparison. + * - The results are returned in chronological order, but the last commit in the + * returned list may not be the most recent one in the entire set if there are + * more pages of results. + * + * For more information on working with pagination, see + * "[Using pagination in the REST API](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api)." + * + * **Signature verification object** + * + * The response will include a `verification` object that describes the result of + * verifying the commit's signature. The `verification` object includes the + * following fields: + * + * | Name | Type | Description | + * | ------------- | --------- | ------------------------------------------------------------------------------------------------ | + * | `verified` | `boolean` | Indicates whether GitHub considers the signature in this commit to be verified. | + * | `reason` | `string` | The reason for verified value. Possible values and their meanings are enumerated in table below. | + * | `signature` | `string` | The signature that was extracted from the commit. | + * | `payload` | `string` | The value that was signed. | + * | `verified_at` | `string` | The date the signature was verified by GitHub. | + * + * These are the possible values for `reason` in the `verification` object: + * + * | Value | Description | + * | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------- | + * | `expired_key` | The key that made the signature is expired. | + * | `not_signing_key` | The "signing" flag is not among the usage flags in the GPG key that made the signature. | + * | `gpgverify_error` | There was an error communicating with the signature verification service. | + * | `gpgverify_unavailable` | The signature verification service is currently unavailable. | + * | `unsigned` | The object does not include a signature. | + * | `unknown_signature_type` | A non-PGP signature was found in the commit. | + * | `no_user` | No user was associated with the `committer` email address in the commit. | + * | `unverified_email` | The `committer` email address in the commit was associated with a user, but the email address is not verified on their account. | + * | `bad_email` | The `committer` email address in the commit is not included in the identities of the PGP key that made the signature. | + * | `unknown_key` | The key that made the signature has not been registered with any user's account. | + * | `malformed_signature` | There was an error parsing the signature. | + * | `invalid` | The signature could not be cryptographically verified using the key whose key-id was found in the signature. | + * | `valid` | None of the above errors applied, so the signature is considered to be verified. | + * + * @example + * ```ts + * const response = await client.repos.compareCommits( + * 'basehead', + * { owner: 'owner', repo: 'repo' }, + * ); + * ``` + */ + compareCommits(basehead, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/compare/${basehead}`, { query, ...options }); + } + /** + * Users with push access in a repository can create commit statuses for a given + * SHA. + * + * Note: there is a limit of 1000 statuses per `sha` and `context` within a + * repository. Attempts to create more than 1000 statuses will result in a + * validation error. + * + * @example + * ```ts + * const response = await client.repos.createCommitStatus( + * 'sha', + * { + * owner: 'owner', + * repo: 'repo', + * state: 'success', + * context: 'continuous-integration/jenkins', + * description: 'The build succeeded!', + * target_url: 'https://example.com/build/status', + * }, + * ); + * ``` + */ + createCommitStatus(sha, params, options) { + const { owner = this._client.owner, repo = this._client.repo, ...body } = params; + return this._client.post(path2`/repos/${owner}/${repo}/statuses/${sha}`, { body, ...options }); } - } - if (typeof filter === "function") { - obj = filter(prefix, obj); - } else if (obj instanceof Date) { - obj = serializeDate?.(obj); - } else if (generateArrayPrefix === "comma" && isArray2(obj)) { - obj = maybe_map2(obj, function(value) { - if (value instanceof Date) { - return serializeDate?.(value); - } - return value; - }); - } - if (obj === null) { - if (strictNullHandling) { - return encoder && !encodeValuesOnly ? ( - // @ts-expect-error - encoder(prefix, defaults2.encoder, charset, "key", format) - ) : prefix; + /** + * You can use this endpoint to trigger a webhook event called + * `repository_dispatch` when you want activity that happens outside of GitHub to + * trigger a GitHub Actions workflow or GitHub App webhook. You must configure your + * GitHub Actions workflow or GitHub App to run when the `repository_dispatch` + * event occurs. For an example `repository_dispatch` webhook payload, see + * "[RepositoryDispatchEvent](https://docs.github.com/webhooks/event-payloads/#repository_dispatch)." + * + * The `client_payload` parameter is available for any extra information that your + * workflow might need. This parameter is a JSON payload that will be passed on + * when the webhook event is dispatched. For example, the `client_payload` can + * include a message that a user would like to send using a GitHub Actions + * workflow. Or the `client_payload` can be used as a test to debug your workflow. + * + * This input example shows how you can use the `client_payload` as a test to debug + * your workflow. + * + * OAuth app tokens and personal access tokens (classic) need the `repo` scope to + * use this endpoint. + * + * @example + * ```ts + * await client.repos.createDispatchEvent({ + * owner: 'owner', + * repo: 'repo', + * event_type: 'on-demand-test', + * client_payload: { unit: false, integration: true }, + * }); + * ``` + */ + createDispatchEvent(params, options) { + const { owner = this._client.owner, repo = this._client.repo, ...body } = params; + return this._client.post(path2`/repos/${owner}/${repo}/dispatches`, { + body, + ...options, + headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + }); } - obj = ""; - } - if (is_non_nullish_primitive2(obj) || is_buffer2(obj)) { - if (encoder) { - const key_value = encodeValuesOnly ? prefix : encoder(prefix, defaults2.encoder, charset, "key", format); - return [ - formatter?.(key_value) + "=" + // @ts-expect-error - formatter?.(encoder(obj, defaults2.encoder, charset, "value", format)) - ]; + /** + * Creates a new repository in the specified organization. The authenticated user + * must be a member of the organization. + * + * OAuth app tokens and personal access tokens (classic) need the `public_repo` or + * `repo` scope to create a public repository, and `repo` scope to create a private + * repository. + * + * @example + * ```ts + * const fullRepository = await client.repos.createForOrg( + * 'org', + * { + * name: 'Hello-World', + * description: 'This is your first repository', + * has_issues: true, + * has_projects: true, + * has_wiki: true, + * homepage: 'https://github.com', + * }, + * ); + * ``` + */ + createForOrg(org, body, options) { + return this._client.post(path2`/orgs/${org}/repos`, { body, ...options }); } - return [formatter?.(prefix) + "=" + formatter?.(String(obj))]; - } - const values = []; - if (typeof obj === "undefined") { - return values; - } - let obj_keys; - if (generateArrayPrefix === "comma" && isArray2(obj)) { - if (encodeValuesOnly && encoder) { - obj = maybe_map2(obj, encoder); + /** + * Creates a new repository using a repository template. Use the `template_owner` + * and `template_repo` route parameters to specify the repository to use as the + * template. If the repository is not public, the authenticated user must own or be + * a member of an organization that owns the repository. To check if a repository + * is available to use as a template, get the repository's information using the + * [Get a repository](https://docs.github.com/rest/repos/repos#get-a-repository) + * endpoint and check that the `is_template` key is `true`. + * + * OAuth app tokens and personal access tokens (classic) need the `public_repo` or + * `repo` scope to create a public repository, and `repo` scope to create a private + * repository. + * + * @example + * ```ts + * const fullRepository = + * await client.repos.createFromTemplate('template_repo', { + * template_owner: 'template_owner', + * name: 'Hello-World', + * description: 'This is your first repository', + * owner: 'octocat', + * }); + * ``` + */ + createFromTemplate(templateRepo, params, options) { + const { template_owner, ...body } = params; + return this._client.post(path2`/repos/${template_owner}/${templateRepo}/generate`, { body, ...options }); } - obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; - } else if (isArray2(filter)) { - obj_keys = filter; - } else { - const keys = Object.keys(obj); - obj_keys = sort ? keys.sort(sort) : keys; - } - const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix); - const adjusted_prefix = commaRoundTrip && isArray2(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix; - if (allowEmptyArrays && isArray2(obj) && obj.length === 0) { - return adjusted_prefix + "[]"; - } - for (let j = 0; j < obj_keys.length; ++j) { - const key = obj_keys[j]; - const value = ( - // @ts-ignore - typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key] - ); - if (skipNulls && value === null) { - continue; + /** + * Gets a redirect URL to download a tar archive for a repository. If you omit + * `:ref`, the repository’s default branch (usually `main`) will be used. Please + * make sure your HTTP framework is configured to follow redirects or you will need + * to use the `Location` header to make a second `GET` request. + * + * > [!NOTE] For private repositories, these links are temporary and expire after + * > five minutes. + * + * @example + * ```ts + * await client.repos.downloadTarball('ref', { + * owner: 'owner', + * repo: 'repo', + * }); + * ``` + */ + downloadTarball(ref, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/tarball/${ref}`, { + ...options, + headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + }); } - const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key; - const key_prefix = isArray2(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]"); - sideChannel.set(object, step); - const valueSideChannel = /* @__PURE__ */ new WeakMap(); - valueSideChannel.set(sentinel2, sideChannel); - push_to_array2(values, inner_stringify2( - value, - key_prefix, - generateArrayPrefix, - commaRoundTrip, - allowEmptyArrays, - strictNullHandling, - skipNulls, - encodeDotInKeys, - // @ts-ignore - generateArrayPrefix === "comma" && encodeValuesOnly && isArray2(obj) ? null : encoder, - filter, - sort, - allowDots, - serializeDate, - format, - formatter, - encodeValuesOnly, - charset, - valueSideChannel - )); - } - return values; -} -function normalize_stringify_options2(opts = defaults2) { - if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") { - throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); - } - if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") { - throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided"); - } - if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") { - throw new TypeError("Encoder has to be a function."); - } - const charset = opts.charset || defaults2.charset; - if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { - throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); - } - let format = default_format2; - if (typeof opts.format !== "undefined") { - if (!has2(formatters2, opts.format)) { - throw new TypeError("Unknown format option provided."); + /** + * Gets a redirect URL to download a zip archive for a repository. If you omit + * `:ref`, the repository’s default branch (usually `main`) will be used. Please + * make sure your HTTP framework is configured to follow redirects or you will need + * to use the `Location` header to make a second `GET` request. + * + * > [!NOTE] For private repositories, these links are temporary and expire after + * > five minutes. If the repository is empty, you will receive a 404 when you + * > follow the redirect. + * + * @example + * ```ts + * await client.repos.downloadZipball('ref', { + * owner: 'owner', + * repo: 'repo', + * }); + * ``` + */ + downloadZipball(ref, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/zipball/${ref}`, { + ...options, + headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + }); } - format = opts.format; - } - const formatter = formatters2[format]; - let filter = defaults2.filter; - if (typeof opts.filter === "function" || isArray2(opts.filter)) { - filter = opts.filter; - } - let arrayFormat; - if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators2) { - arrayFormat = opts.arrayFormat; - } else if ("indices" in opts) { - arrayFormat = opts.indices ? "indices" : "repeat"; - } else { - arrayFormat = defaults2.arrayFormat; - } - if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") { - throw new TypeError("`commaRoundTrip` must be a boolean, or absent"); - } - const allowDots = typeof opts.allowDots === "undefined" ? !!opts.encodeDotInKeys === true ? true : defaults2.allowDots : !!opts.allowDots; - return { - addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults2.addQueryPrefix, - // @ts-ignore - allowDots, - allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults2.allowEmptyArrays, - arrayFormat, - charset, - charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults2.charsetSentinel, - commaRoundTrip: !!opts.commaRoundTrip, - delimiter: typeof opts.delimiter === "undefined" ? defaults2.delimiter : opts.delimiter, - encode: typeof opts.encode === "boolean" ? opts.encode : defaults2.encode, - encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults2.encodeDotInKeys, - encoder: typeof opts.encoder === "function" ? opts.encoder : defaults2.encoder, - encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults2.encodeValuesOnly, - filter, - format, - formatter, - serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults2.serializeDate, - skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults2.skipNulls, - // @ts-ignore - sort: typeof opts.sort === "function" ? opts.sort : null, - strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults2.strictNullHandling - }; -} -function stringify2(object, opts = {}) { - let obj = object; - const options = normalize_stringify_options2(opts); - let obj_keys; - let filter; - if (typeof options.filter === "function") { - filter = options.filter; - obj = filter("", obj); - } else if (isArray2(options.filter)) { - filter = options.filter; - obj_keys = filter; - } - const keys = []; - if (typeof obj !== "object" || obj === null) { - return ""; - } - const generateArrayPrefix = array_prefix_generators2[options.arrayFormat]; - const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip; - if (!obj_keys) { - obj_keys = Object.keys(obj); - } - if (options.sort) { - obj_keys.sort(options.sort); - } - const sideChannel = /* @__PURE__ */ new WeakMap(); - for (let i = 0; i < obj_keys.length; ++i) { - const key = obj_keys[i]; - if (options.skipNulls && obj[key] === null) { - continue; + /** + * Enables an authenticated GitHub App to find the repository's installation + * information. The installation's account type will be either an organization or a + * user account, depending which account the repository belongs to. + * + * You must use a + * [JWT](https://docs.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) + * to access this endpoint. + * + * @example + * ```ts + * const installation = await client.repos.getInstallationInfo( + * { owner: 'owner', repo: 'repo' }, + * ); + * ``` + */ + getInstallationInfo(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/installation`, options); } - push_to_array2(keys, inner_stringify2( - obj[key], - key, - // @ts-expect-error - generateArrayPrefix, - commaRoundTrip, - options.allowEmptyArrays, - options.strictNullHandling, - options.skipNulls, - options.encodeDotInKeys, - options.encode ? options.encoder : null, - options.filter, - options.sort, - options.allowDots, - options.serializeDate, - options.format, - options.formatter, - options.encodeValuesOnly, - options.charset, - sideChannel - )); - } - const joined = keys.join(options.delimiter); - let prefix = options.addQueryPrefix === true ? "?" : ""; - if (options.charsetSentinel) { - if (options.charset === "iso-8859-1") { - prefix += "utf8=%26%2310003%3B&"; - } else { - prefix += "utf8=%E2%9C%93&"; + /** + * This method returns the contents of the repository's license file, if one is + * detected. + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.raw+json`**: Returns the raw contents of the + * license. + * - **`application/vnd.github.html+json`**: Returns the license contents in HTML. + * Markup languages are rendered to HTML using GitHub's open-source + * [Markup library](https://github.com/github/markup). + * + * @example + * ```ts + * const response = await client.repos.getLicense({ + * owner: 'owner', + * repo: 'repo', + * }); + * ``` + */ + getLicense(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/license`, { query, ...options }); } - } - return joined.length > 0 ? prefix + joined : ""; -} - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/utils/log.mjs -var levelNumbers2 = { - off: 0, - error: 200, - warn: 300, - info: 400, - debug: 500 -}; -var parseLogLevel2 = (maybeLevel, sourceName, client) => { - if (!maybeLevel) { - return void 0; - } - if (hasOwn2(levelNumbers2, maybeLevel)) { - return maybeLevel; - } - loggerFor2(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers2))}`); - return void 0; -}; -function noop2() { -} -function makeLogFn2(fnLevel, logger2, logLevel) { - if (!logger2 || levelNumbers2[fnLevel] > levelNumbers2[logLevel]) { - return noop2; - } else { - return logger2[fnLevel].bind(logger2); - } -} -var noopLogger2 = { - error: noop2, - warn: noop2, - info: noop2, - debug: noop2 -}; -var cachedLoggers2 = /* @__PURE__ */ new WeakMap(); -function loggerFor2(client) { - const logger2 = client.logger; - const logLevel = client.logLevel ?? "off"; - if (!logger2) { - return noopLogger2; - } - const cachedLogger = cachedLoggers2.get(logger2); - if (cachedLogger && cachedLogger[0] === logLevel) { - return cachedLogger[1]; - } - const levelLogger = { - error: makeLogFn2("error", logger2, logLevel), - warn: makeLogFn2("warn", logger2, logLevel), - info: makeLogFn2("info", logger2, logLevel), - debug: makeLogFn2("debug", logger2, logLevel) - }; - cachedLoggers2.set(logger2, [logLevel, levelLogger]); - return levelLogger; -} -var formatRequestDetails2 = (details) => { - if (details.options) { - details.options = { ...details.options }; - delete details.options["headers"]; - } - if (details.headers) { - details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ - name, - name.toLowerCase() === "authorization" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value - ])); - } - if ("retryOfRequestLogID" in details) { - if (details.retryOfRequestLogID) { - details.retryOf = details.retryOfRequestLogID; + /** + * Get the code security configuration that manages a repository's code security + * settings. + * + * The authenticated user must be an administrator or security manager for the + * organization to use this endpoint. + * + * OAuth app tokens and personal access tokens (classic) need the `repo` scope to + * use this endpoint. + * + * @example + * ```ts + * const response = + * await client.repos.getSecurityConfiguration({ + * owner: 'owner', + * repo: 'repo', + * }); + * ``` + */ + getSecurityConfiguration(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/code-security-configuration`, options); + } + /** + * Lists a detailed history of changes to a repository, such as pushes, merges, + * force pushes, and branch changes, and associates these changes with commits and + * users. + * + * For more information about viewing repository activity, see + * "[Viewing activity and data for your repository](https://docs.github.com/repositories/viewing-activity-and-data-for-your-repository)." + * + * @example + * ```ts + * const response = await client.repos.listActivity({ + * owner: 'owner', + * repo: 'repo', + * }); + * ``` + */ + listActivity(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/activity`, { query, ...options }); } - delete details.retryOfRequestLogID; - } - return details; -}; - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/parse.mjs -async function defaultParseResponse2(client, props) { - const { response, requestLogID, retryOfRequestLogID, startTime } = props; - const body = await (async () => { - if (response.status === 204) { - return null; + /** + * > [!NOTE] This API is not built to serve real-time use cases. Depending on the + * > time of day, event latency can be anywhere from 30s to 6h. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const repoListEventsResponse of client.repos.listEvents( + * { owner: 'owner', repo: 'repo' }, + * )) { + * // ... + * } + * ``` + */ + listEvents(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.getAPIList(path2`/repos/${owner}/${repo}/events`, NumberedPage, { query, ...options }); } - if (props.options.__binaryResponse) { - return response; + /** + * Lists repositories that the authenticated user has explicit permission (`:read`, + * `:write`, or `:admin`) to access. + * + * The authenticated user has explicit permission to access repositories they own, + * repositories where they are a collaborator, and repositories that they can + * access through an organization membership. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const repository of client.repos.listForCurrentUser()) { + * // ... + * } + * ``` + */ + listForCurrentUser(query = {}, options) { + return this._client.getAPIList("/user/repos", NumberedPage, { query, ...options }); } - const contentType = response.headers.get("content-type"); - const mediaType = contentType?.split(";")[0]?.trim(); - const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json"); - if (isJSON) { - const contentLength = response.headers.get("content-length"); - if (contentLength === "0") { - return void 0; - } - const json = await response.json(); - return json; + /** + * Lists repositories for the specified organization. + * + * > [!NOTE] In order to see the `security_and_analysis` block for a repository you + * > must have admin permissions for the repository or be an owner or security + * > manager for the organization that owns the repository. For more information, + * > see + * > "[Managing security managers in your organization](https://docs.github.com/organizations/managing-peoples-access-to-your-organization-with-roles/managing-security-managers-in-your-organization)." + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const minimalRepository of client.repos.listForOrg( + * 'org', + * )) { + * // ... + * } + * ``` + */ + listForOrg(org, query = {}, options) { + return this._client.getAPIList(path2`/orgs/${org}/repos`, NumberedPage, { + query, + ...options + }); } - const text = await response.text(); - return text; - })(); - loggerFor2(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails2({ - retryOfRequestLogID, - url: response.url, - status: response.status, - body, - durationMs: Date.now() - startTime - })); - return body; -} - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/core/api-promise.mjs -var _APIPromise_client2; -var APIPromise2 = /* @__PURE__ */ (() => { - class APIPromise4 extends Promise { - constructor(client, responsePromise, parseResponse = defaultParseResponse2) { - super((resolve) => { - resolve(null); + /** + * Lists public repositories for the specified user. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const minimalRepository of client.repos.listForUser( + * 'username', + * )) { + * // ... + * } + * ``` + */ + listForUser(username, query = {}, options) { + return this._client.getAPIList(path2`/users/${username}/repos`, NumberedPage, { + query, + ...options }); - this.responsePromise = responsePromise; - this.parseResponse = parseResponse; - _APIPromise_client2.set(this, void 0); - __classPrivateFieldSet2(this, _APIPromise_client2, client, "f"); } - _thenUnwrap(transform) { - return new APIPromise4(__classPrivateFieldGet2(this, _APIPromise_client2, "f"), this.responsePromise, async (client, props) => transform(await this.parseResponse(client, props), props)); + /** + * Lists all public repositories in the order that they were created. + * + * Note: + * + * - For GitHub Enterprise Server, this endpoint will only list repositories + * available to all users on the enterprise. + * - Pagination is powered exclusively by the `since` parameter. Use the + * [Link header](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api#using-link-headers) + * to get the URL for the next page of repositories. + * + * @example + * ```ts + * const minimalRepositories = await client.repos.listPublic(); + * ``` + */ + listPublic(query = {}, options) { + return this._client.get("/repositories", { query, ...options }); } /** - * Gets the raw `Response` instance instead of parsing the response - * data. + * Lists the people that have starred the repository. * - * If you want to parse the response body but still get the `Response` - * instance, you can use {@link withResponse()}. + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.star+json`**: Includes a timestamp of when the star + * was created. + * + * @example + * ```ts + * const response = await client.repos.listStargazers({ + * owner: 'owner', + * repo: 'repo', + * }); + * ``` + */ + listStargazers(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/stargazers`, { query, ...options }); + } + /** + * Lists repositories the authenticated user has starred. + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.star+json`**: Includes a timestamp of when the star + * was created. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const repository of client.repos.listStarred()) { + * // ... + * } + * ``` + */ + listStarred(query = {}, options) { + return this._client.getAPIList("/user/starred", NumberedPage, { query, ...options }); + } + /** + * Lists the people watching the specified repository. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const simpleUser of client.repos.listWatchers({ + * owner: 'owner', + * repo: 'repo', + * })) { + * // ... + * } + * ``` + */ + listWatchers(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.getAPIList(path2`/repos/${owner}/${repo}/subscribers`, NumberedPage, { query, ...options }); + } + /** + * Merge a branch + * + * @example + * ```ts + * const commit = await client.repos.mergeBranch({ + * owner: 'owner', + * repo: 'repo', + * base: 'master', + * head: 'cool_feature', + * commit_message: 'Shipped cool_feature!', + * }); + * ``` + */ + mergeBranch(params, options) { + const { owner = this._client.owner, repo = this._client.repo, ...body } = params; + return this._client.post(path2`/repos/${owner}/${repo}/merges`, { body, ...options }); + } + /** + * Note that you'll need to set `Content-Length` to zero when calling out to this + * endpoint. For more information, see + * "[HTTP method](https://docs.github.com/rest/guides/getting-started-with-the-rest-api#http-method)." + * + * @example + * ```ts + * await client.repos.star({ owner: 'owner', repo: 'repo' }); + * ``` + */ + star(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; + return this._client.put(path2`/user/starred/${owner}/${repo}`, { + ...options, + headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + }); + } + /** + * Sync a branch of a forked repository to keep it up-to-date with the upstream + * repository. + * + * @example + * ```ts + * const response = await client.repos.syncFork({ + * owner: 'owner', + * repo: 'repo', + * branch: 'main', + * }); + * ``` + */ + syncFork(params, options) { + const { owner = this._client.owner, repo = this._client.repo, ...body } = params; + return this._client.post(path2`/repos/${owner}/${repo}/merge-upstream`, { body, ...options }); + } + /** + * A transfer request will need to be accepted by the new owner when transferring a + * personal repository to another user. The response will contain the original + * `owner`, and the transfer will continue asynchronously. For more details on the + * requirements to transfer personal and organization-owned repositories, see + * [about repository transfers](https://docs.github.com/articles/about-repository-transfers/). * - * 👋 Getting the wrong TypeScript type for `Response`? - * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` - * to your `tsconfig.json`. + * @example + * ```ts + * const minimalRepository = await client.repos.transfer({ + * owner: 'owner', + * repo: 'repo', + * new_owner: 'github', + * new_name: 'octorepo', + * team_ids: [12, 345], + * }); + * ``` */ - asResponse() { - return this.responsePromise.then((p) => p.response); + transfer(params, options) { + const { owner = this._client.owner, repo = this._client.repo, ...body } = params; + return this._client.post(path2`/repos/${owner}/${repo}/transfer`, { body, ...options }); } /** - * Gets the parsed response data and the raw `Response` instance. - * - * If you just want to get the raw `Response` instance without parsing it, - * you can use {@link asResponse()}. + * Unstar a repository that the authenticated user has previously starred. * - * 👋 Getting the wrong TypeScript type for `Response`? - * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` - * to your `tsconfig.json`. + * @example + * ```ts + * await client.repos.unstar({ owner: 'owner', repo: 'repo' }); + * ``` */ - async withResponse() { - const [data, response] = await Promise.all([this.parse(), this.asResponse()]); - return { data, response }; - } - parse() { - if (!this.parsedPromise) { - this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet2(this, _APIPromise_client2, "f"), data)); - } - return this.parsedPromise; - } - then(onfulfilled, onrejected) { - return this.parse().then(onfulfilled, onrejected); - } - catch(onrejected) { - return this.parse().catch(onrejected); - } - finally(onfinally) { - return this.parse().finally(onfinally); + unstar(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; + return this._client.delete(path2`/user/starred/${owner}/${repo}`, { + ...options, + headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + }); } } - _APIPromise_client2 = /* @__PURE__ */ new WeakMap(); - return APIPromise4; + BaseRepos6._key = Object.freeze(["repos"]); + return BaseRepos6; })(); -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/utils/env.mjs +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/utils/env.mjs var readEnv2 = (env) => { if (typeof globalThis.process !== "undefined") { return globalThis.process.env?.[env]?.trim() ?? void 0; @@ -15330,17 +14586,72 @@ var readEnv2 = (env) => { return void 0; }; -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/client.mjs -var _BaseGitLab_instances; -var _BaseGitLab_encoder; -var _BaseGitLab_baseURLOverridden; -var BaseGitLab = /* @__PURE__ */ (() => { - class BaseGitLab2 { +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/lib/auth.mjs +var import_jsonwebtoken = __toESM(require_jsonwebtoken(), 1); +async function getAuthToken({ authMethods, owner, repo, logger: logger2 }) { + const method = authMethods.find((method2) => method2.owner === owner) ?? authMethods.at(-1); + if (!method || method.owner !== owner && method.owner !== "*") { + throw new Error("No matching auth method found. Did you set a fallback auth method, with owner *?"); + } + if ("token" in method) { + return { authToken: method.token, expires: method.expires }; + } + const appAuth = await getAppToken(method); + const client = createClient({ + owner, + repo, + authToken: appAuth.authToken, + resources: [BaseRepos3, BaseOrgs, BaseInstallations] + }); + let installationId = method.installationId; + try { + if (!installationId) { + if (repo) { + const { id } = await client.repos.getInstallationInfo(); + installationId = id; + } else { + const { id } = await client.orgs.retrieveInstallation(owner); + installationId = id; + } + } + } catch (e) { + logger2?.warn(`No installation ID found for ${owner}/${repo}, using app token instead`, e); + } + if (!installationId) { + return appAuth; + } + try { + const { token, expires_at } = await client.apps.installations.createAccessToken(installationId); + return { authToken: token, expires: new Date(expires_at) }; + } catch (e) { + logger2?.warn(`Failed to get installation token for ${installationId}, using app token instead`, e); + } + return appAuth; +} +async function getAppToken(method) { + const iat = Math.floor(Date.now() / 1e3) - 30; + const exp = iat + 60 * 10; + const appToken = import_jsonwebtoken.default.sign({ iat, exp, iss: method.appId }, method.privateKey, { + algorithm: "RS256" + }); + const appTokenExpires = new Date(exp * 1e3); + return { authToken: appToken, expires: appTokenExpires }; +} + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/client.mjs +var _BaseGitHub_instances; +var _BaseGitHub_encoder; +var _BaseGitHub_baseURLOverridden; +var BaseGitHub = /* @__PURE__ */ (() => { + class BaseGitHub3 { /** - * API Client for interfacing with the GitLab API. + * API Client for interfacing with the GitHub API. * - * @param {string | undefined} [opts.apiToken=process.env['GITLAB_API_TOKEN'] ?? undefined] - * @param {string} [opts.baseURL=process.env['GITLAB_BASE_URL'] ?? https://gitlab.com/api/v4] - Override the default base URL for the API. + * @param {string | null | undefined} [opts.authToken=process.env['GITHUB_AUTH_TOKEN'] ?? null] + * @param {string | null | undefined} [opts.owner] + * @param {string | null | undefined} [opts.repo] + * @param {string | null | undefined} [opts.webhookSecret=process.env['GITHUB_WEBHOOK_SECRET'] ?? null] + * @param {string} [opts.baseURL=process.env['GITHUB_BASE_URL'] ?? https://api.github.com] - Override the default base URL for the API. * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. @@ -15348,29 +14659,32 @@ var BaseGitLab = /* @__PURE__ */ (() => { * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. */ - constructor({ baseURL = readEnv2("GITLAB_BASE_URL"), apiToken = readEnv2("GITLAB_API_TOKEN"), ...opts } = {}) { - _BaseGitLab_instances.add(this); - _BaseGitLab_encoder.set(this, void 0); - if (apiToken === void 0) { - throw new GitLabError("The GITLAB_API_TOKEN environment variable is missing or empty; either provide it, or instantiate the GitLab client with an apiToken option, like new GitLab({ apiToken: 'My API Token' })."); - } + constructor({ baseURL = readEnv2("GITHUB_BASE_URL"), authToken = readEnv2("GITHUB_AUTH_TOKEN") ?? null, owner = null, repo = null, webhookSecret = readEnv2("GITHUB_WEBHOOK_SECRET") ?? null, ...opts } = {}) { + _BaseGitHub_instances.add(this); + _BaseGitHub_encoder.set(this, void 0); const options = { - apiToken, + authToken, + owner, + repo, + webhookSecret, ...opts, - baseURL: baseURL || `https://gitlab.com/api/v4` + baseURL: baseURL || `https://api.github.com` }; this.baseURL = options.baseURL; - this.timeout = options.timeout ?? BaseGitLab2.DEFAULT_TIMEOUT; + this.timeout = options.timeout ?? BaseGitHub3.DEFAULT_TIMEOUT; this.logger = options.logger ?? console; const defaultLogLevel = "warn"; this.logLevel = defaultLogLevel; - this.logLevel = parseLogLevel2(options.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel2(readEnv2("GITLAB_LOG"), "process.env['GITLAB_LOG']", this) ?? defaultLogLevel; + this.logLevel = parseLogLevel2(options.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel2(readEnv2("GITHUB_LOG"), "process.env['GITHUB_LOG']", this) ?? defaultLogLevel; this.fetchOptions = options.fetchOptions; this.maxRetries = options.maxRetries ?? 2; this.fetch = options.fetch ?? getDefaultFetch2(); - __classPrivateFieldSet2(this, _BaseGitLab_encoder, FallbackEncoder2, "f"); + __classPrivateFieldSet2(this, _BaseGitHub_encoder, FallbackEncoder2, "f"); this._options = options; - this.apiToken = apiToken; + this.authToken = authToken; + this.owner = owner; + this.repo = repo; + this.webhookSecret = webhookSecret; } /** * Create a new client instance re-using the same options given to the current client with optional overriding. @@ -15385,117 +14699,28 @@ var BaseGitLab = /* @__PURE__ */ (() => { logLevel: this.logLevel, fetch: this.fetch, fetchOptions: this.fetchOptions, - apiToken: this.apiToken, + authToken: this.authToken, + owner: this.owner, + repo: this.repo, + webhookSecret: this.webhookSecret, ...options }); return client; } /** - * Execute a GLQL (GitLab Query Language) query - */ - glql(body, options) { - return this.post("/glql", { body, ...options }); - } - /** - * This feature was introduced in GitLab 11.0. - */ - markdown(body, options) { - return this.post("/markdown", { body, ...options }); - } - /** - * This feature was introduced in GitLab 17.5. \ - * This feature is currently in an experimental state. \ - * This feature is behind the `allow_organization_creation` feature flag. \ - * In GitLab 18.3, feature flag changed to `organization_switching`. - */ - organizations(body, options) { - return this.post("/organizations", multipartFormRequestOptions({ body, ...options }, this)); - } - /** - * Return avatar url for a user - */ - retrieveAvatar(query, options) { - return this.get("/avatar", { query, ...options }); - } - /** - * Get a list of all deploy tokens across the GitLab instance. This endpoint - * requires administrator access. This feature was introduced in GitLab 12.9. - */ - retrieveDeployTokens(query = {}, options) { - return this.get("/deploy_tokens", { query, ...options }); - } - /** - * This feature was introduced in GitLab 17.9. It will be removed in 18.0. - */ - retrieveDiscoverCertBasedClusters(query, options) { - return this.get("/discover-cert-based-clusters", { query, ...options }); - } - /** - * This feature was introduced in GitLab 9.3. - */ - retrieveEvents(query = {}, options) { - return this.get("/events", { query, ...options }); - } - /** - * Get a list of all experiments. Each experiment has an enabled status that - * indicates whetherthe experiment is enabled globally, or only in specific - * contexts. - */ - retrieveExperiments(options) { - return this.get("/experiments", options); - } - /** - * Get currently authenticated user's issues statistics - */ - retrieveIssuesStatistics(query = {}, options) { - return this.get("/issues_statistics", { - query, - ...options, - headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) - }); - } - /** - * Get a list of licenses - */ - retrieveLicenses(options) { - return this.get("/licenses", options); - } - /** - * Get all merge requests the authenticated user has access to. By default it - * returns only merge requests created by the current user. To get all merge - * requests, use parameter `scope=all`. - */ - retrieveMergeRequests(query = {}, options) { - return this.get("/merge_requests", { query, ...options }); - } - /** - * This feature was introduced in GitLab 15.2. - */ - retrieveMetadata(options) { - return this.get("/metadata", options); - } - /** - * This feature was introduced in GitLab 10.5. - */ - retrieveSearch(query, options) { - return this.get("/search", { - query, - ...options, - headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) - }); - } - /** - * Assigned open issues, assigned MRs and pending todos count + * Get Hypermedia links to resources accessible in GitHub's REST API */ - retrieveUserCounts(options) { - return this.get("/user_counts", options); + retrieve(options) { + return this.get("/", options); } /** - * This feature was introduced in GitLab 8.13 and deprecated in 15.5. We recommend - * you instead use the Metadata API. + * Get a random sentence from the Zen of GitHub */ - retrieveVersion(options) { - return this.get("/version", options); + zen(options) { + return this.get("/zen", { + ...options, + headers: buildHeaders2([{ Accept: "text/plain" }, options?.headers]) + }); } defaultQuery() { return this._options.defaultQuery; @@ -15504,7 +14729,32 @@ var BaseGitLab = /* @__PURE__ */ (() => { return; } async authHeaders(opts) { - return buildHeaders2([{ Authorization: `Bearer ${this.apiToken}` }]); + if (this.authToken == null) { + return void 0; + } + return buildHeaders2([{ Authorization: `Bearer ${this.authToken}` }]); + } + /** + * Given a list of available auth methods, get an auth token to access the + * given GitHub `owner` (and optionally `repo`), and set it on this client. + */ + async getAuthToken(opts) { + if (this.authToken != null) { + return this.authToken; + } + const owner = opts.owner ?? this.owner; + const repo = opts.repo ?? this.repo; + if (owner == null) { + throw new Error("Specify an owner to get a token for."); + } + const { authToken } = await getAuthToken({ + authMethods: opts.authMethods, + owner, + repo, + logger: this.logger + }); + this.authToken = authToken; + return authToken; } stringifyQuery(query) { return stringify2(query, { arrayFormat: "comma" }); @@ -15519,7 +14769,7 @@ var BaseGitLab = /* @__PURE__ */ (() => { return APIError2.generate(status, error, message, headers); } buildURL(path7, query, defaultBaseURL) { - const baseURL = !__classPrivateFieldGet2(this, _BaseGitLab_instances, "m", _BaseGitLab_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL; + const baseURL = !__classPrivateFieldGet2(this, _BaseGitHub_instances, "m", _BaseGitHub_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL; const url = isAbsoluteURL2(path7) ? new URL(path7) : new URL(baseURL + (baseURL.endsWith("/") && path7.startsWith("/") ? path7.slice(1) : path7)); const defaultQuery = this.defaultQuery(); if (!isEmptyObj2(defaultQuery)) { @@ -15558,4341 +14808,5108 @@ var BaseGitLab = /* @__PURE__ */ (() => { delete(path7, opts) { return this.methodRequest("delete", path7, opts); } - methodRequest(method, path7, opts) { - return this.request(Promise.resolve(opts).then((opts2) => { - return { method, path: path7, ...opts2 }; - })); + methodRequest(method, path7, opts) { + return this.request(Promise.resolve(opts).then((opts2) => { + return { method, path: path7, ...opts2 }; + })); + } + request(options, remainingRetries = null) { + return new APIPromise2(this, this.makeRequest(options, remainingRetries, void 0)); + } + async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { + const options = await optionsInput; + const maxRetries = options.maxRetries ?? this.maxRetries; + if (retriesRemaining == null) { + retriesRemaining = maxRetries; + } + await this.prepareOptions(options); + const { req, url, timeout } = await this.buildRequest(options, { + retryCount: maxRetries - retriesRemaining + }); + await this.prepareRequest(req, { url, options }); + const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0"); + const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`; + const startTime = Date.now(); + loggerFor2(this).debug(`[${requestLogID}] sending request`, formatRequestDetails2({ + retryOfRequestLogID, + method: options.method, + url, + options, + headers: req.headers + })); + if (options.signal?.aborted) { + throw new APIUserAbortError2(); + } + const controller = new AbortController(); + const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError2); + const headersTime = Date.now(); + if (response instanceof globalThis.Error) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + if (options.signal?.aborted) { + throw new APIUserAbortError2(); + } + const isTimeout = isAbortError2(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : "")); + if (retriesRemaining) { + loggerFor2(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`); + loggerFor2(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails2({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); + } + loggerFor2(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`); + loggerFor2(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails2({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + if (isTimeout) { + throw new APIConnectionTimeoutError2(); + } + throw new APIConnectionError2({ cause: response }); + } + const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`; + if (!response.ok) { + const shouldRetry = await this.shouldRetry(response); + if (retriesRemaining && shouldRetry) { + const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`; + await CancelReadableStream2(response.body); + loggerFor2(this).info(`${responseInfo} - ${retryMessage2}`); + loggerFor2(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails2({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); + } + const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; + loggerFor2(this).info(`${responseInfo} - ${retryMessage}`); + const errText = await response.text().catch((err2) => castToError2(err2).message); + const errJSON = safeJSON2(errText); + const errMessage = errJSON ? void 0 : errText; + loggerFor2(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails2({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + message: errMessage, + durationMs: Date.now() - startTime + })); + const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); + throw err; + } + loggerFor2(this).info(responseInfo); + loggerFor2(this).debug(`[${requestLogID}] response start`, formatRequestDetails2({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; + } + getAPIList(path7, Page2, opts) { + return this.requestAPIList(Page2, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path7, ...opts2 })) : { method: "get", path: path7, ...opts }); + } + requestAPIList(Page2, options) { + const request = this.makeRequest(options, null, void 0); + return new PagePromise2(this, request, Page2); + } + async fetchWithTimeout(url, init, ms, controller) { + const { signal, method, ...options } = init || {}; + const abort = this._makeAbort(controller); + if (signal) + signal.addEventListener("abort", abort, { once: true }); + const timeout = setTimeout(abort, ms); + const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body; + const fetchOptions = { + signal: controller.signal, + ...isReadableBody ? { duplex: "half" } : {}, + method: "GET", + ...options + }; + if (method) { + fetchOptions.method = method.toUpperCase(); + } + try { + return await this.fetch.call(void 0, url, fetchOptions); + } finally { + clearTimeout(timeout); + } + } + async shouldRetry(response) { + const shouldRetryHeader = response.headers.get("x-should-retry"); + if (shouldRetryHeader === "true") + return true; + if (shouldRetryHeader === "false") + return false; + if (response.status === 408) + return true; + if (response.status === 409) + return true; + if (response.status === 429) + return true; + if (response.status >= 500) + return true; + return false; + } + async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { + let timeoutMillis; + const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms"); + if (retryAfterMillisHeader) { + const timeoutMs = parseFloat(retryAfterMillisHeader); + if (!Number.isNaN(timeoutMs)) { + timeoutMillis = timeoutMs; + } + } + const retryAfterHeader = responseHeaders?.get("retry-after"); + if (retryAfterHeader && !timeoutMillis) { + const timeoutSeconds = parseFloat(retryAfterHeader); + if (!Number.isNaN(timeoutSeconds)) { + timeoutMillis = timeoutSeconds * 1e3; + } else { + timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); + } + } + if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1e3)) { + const maxRetries = options.maxRetries ?? this.maxRetries; + timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + } + await sleep2(timeoutMillis); + return this.makeRequest(options, retriesRemaining - 1, requestLogID); + } + calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { + const initialRetryDelay = 0.5; + const maxRetryDelay = 8; + const numRetries = maxRetries - retriesRemaining; + const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); + const jitter = 1 - Math.random() * 0.25; + return sleepSeconds * jitter * 1e3; + } + async buildRequest(inputOptions, { retryCount = 0 } = {}) { + const options = { ...inputOptions }; + const { method, path: path7, query, defaultBaseURL } = options; + const url = this.buildURL(path7, query, defaultBaseURL); + if ("timeout" in options) + validatePositiveInteger2("timeout", options.timeout); + options.timeout = options.timeout ?? this.timeout; + const { bodyHeaders, body } = this.buildBody({ options }); + const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); + const req = { + method, + headers: reqHeaders, + ...options.signal && { signal: options.signal }, + ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" }, + ...body && { body }, + ...this.fetchOptions ?? {}, + ...options.fetchOptions ?? {} + }; + return { req, url, timeout: options.timeout }; + } + async buildHeaders({ options, method, bodyHeaders, retryCount }) { + let idempotencyHeaders = {}; + if (this.idempotencyHeader && method !== "get") { + if (!options.idempotencyKey) + options.idempotencyKey = this.defaultIdempotencyKey(); + idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; + } + const headers = buildHeaders2([ + idempotencyHeaders, + { + Accept: "application/json", + "User-Agent": this.getUserAgent(), + "X-Stainless-Retry-Count": String(retryCount), + ...options.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options.timeout / 1e3)) } : {}, + ...getPlatformHeaders2() + }, + await this.authHeaders(options), + this._options.defaultHeaders, + bodyHeaders, + options.headers + ]); + this.validateHeaders(headers); + return headers.values; + } + _makeAbort(controller) { + return () => controller.abort(); } - request(options, remainingRetries = null) { - return new APIPromise2(this, this.makeRequest(options, remainingRetries, void 0)); + buildBody({ options: { body, headers: rawHeaders } }) { + if (!body) { + return { bodyHeaders: void 0, body: void 0 }; + } + const headers = buildHeaders2([rawHeaders]); + if ( + // Pass raw type verbatim + ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && // Preserve legacy string encoding behavior for now + headers.values.has("content-type") || // `Blob` is superset of `File` + globalThis.Blob && body instanceof globalThis.Blob || // `FormData` -> `multipart/form-data` + body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded` + body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`) + globalThis.ReadableStream && body instanceof globalThis.ReadableStream + ) { + return { bodyHeaders: void 0, body }; + } else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) { + return { bodyHeaders: void 0, body: ReadableStreamFrom2(body) }; + } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") { + return { + bodyHeaders: { "content-type": "application/x-www-form-urlencoded" }, + body: this.stringifyQuery(body) + }; + } else { + return __classPrivateFieldGet2(this, _BaseGitHub_encoder, "f").call(this, { body, headers }); + } } - async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { - const options = await optionsInput; - const maxRetries = options.maxRetries ?? this.maxRetries; - if (retriesRemaining == null) { - retriesRemaining = maxRetries; + } + _BaseGitHub_encoder = /* @__PURE__ */ new WeakMap(), _BaseGitHub_instances = /* @__PURE__ */ new WeakSet(), _BaseGitHub_baseURLOverridden = function _BaseGitHub_baseURLOverridden2() { + return this.baseURL !== "https://api.github.com"; + }; + BaseGitHub3.DEFAULT_TIMEOUT = 6e4; + return BaseGitHub3; +})(); + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/tree-shakable.mjs +function createClient(options) { + const client = new BaseGitHub(options); + for (const ResourceClass of options.resources) { + const resourceInstance = new ResourceClass(client); + let object = client; + for (const part of ResourceClass._key.slice(0, -1)) { + if (hasOwn2(object, part)) { + object = object[part]; + } else { + Object.defineProperty(object, part, { + value: object = {}, + configurable: true, + enumerable: true, + writable: true + }); } - await this.prepareOptions(options); - const { req, url, timeout } = await this.buildRequest(options, { - retryCount: maxRetries - retriesRemaining + } + const name = ResourceClass._key.at(-1); + if (!hasOwn2(object, name)) { + Object.defineProperty(object, name, { + value: resourceInstance, + configurable: true, + enumerable: true, + writable: true }); - await this.prepareRequest(req, { url, options }); - const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0"); - const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`; - const startTime = Date.now(); - loggerFor2(this).debug(`[${requestLogID}] sending request`, formatRequestDetails2({ - retryOfRequestLogID, - method: options.method, - url, - options, - headers: req.headers - })); - if (options.signal?.aborted) { - throw new APIUserAbortError2(); - } - const controller = new AbortController(); - const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError2); - const headersTime = Date.now(); - if (response instanceof globalThis.Error) { - const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; - if (options.signal?.aborted) { - throw new APIUserAbortError2(); - } - const isTimeout = isAbortError2(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : "")); - if (retriesRemaining) { - loggerFor2(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`); - loggerFor2(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails2({ - retryOfRequestLogID, - url, - durationMs: headersTime - startTime, - message: response.message - })); - return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); - } - loggerFor2(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`); - loggerFor2(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails2({ - retryOfRequestLogID, - url, - durationMs: headersTime - startTime, - message: response.message - })); - if (isTimeout) { - throw new APIConnectionTimeoutError2(); - } - throw new APIConnectionError2({ cause: response }); + } else { + if (object[name] instanceof APIResource2) { + throw new TypeError(`Resource at ${ResourceClass._key.join(".")} already exists!`); + } else { + object[name] = Object.assign(resourceInstance, object[name]); } - const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`; - if (!response.ok) { - const shouldRetry = await this.shouldRetry(response); - if (retriesRemaining && shouldRetry) { - const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`; - await CancelReadableStream2(response.body); - loggerFor2(this).info(`${responseInfo} - ${retryMessage2}`); - loggerFor2(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails2({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - durationMs: headersTime - startTime - })); - return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); - } - const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; - loggerFor2(this).info(`${responseInfo} - ${retryMessage}`); - const errText = await response.text().catch((err2) => castToError2(err2).message); - const errJSON = safeJSON2(errText); - const errMessage = errJSON ? void 0 : errText; - loggerFor2(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails2({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - message: errMessage, - durationMs: Date.now() - startTime - })); - const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); - throw err; + } + } + return client; +} + +// src/compat/github/context.ts +var fs = __toESM(require("node:fs")); +var cachedContext; +function getGitHubContext() { + if (cachedContext) { + return cachedContext; + } + const [owner, repo] = process.env.GITHUB_REPOSITORY?.split("/") ?? []; + const runID = process.env.GITHUB_RUN_ID; + if (!owner || !repo || !runID) { + throw new Error( + "Expected env vars GITHUB_REPOSITORY and GITHUB_RUN_ID to be set." + ); + } + const host = process.env.GITHUB_SERVER_URL || "https://github.com"; + const apiURL = process.env.GITHUB_API_URL || "https://api.github.com"; + const runURL = `${host}/${owner}/${repo}/actions/runs/${runID}`; + let defaultBranch = null; + let prNumber = null; + try { + const eventPath = process.env.GITHUB_EVENT_PATH; + const payload = eventPath && fs.existsSync(eventPath) && JSON.parse(fs.readFileSync(eventPath, "utf-8")); + const maybeDefaultBranch = payload?.repository?.default_branch; + if (typeof maybeDefaultBranch === "string") { + defaultBranch = maybeDefaultBranch; + } + const maybePRNumber = parseInt( + payload?.pull_request?.number ?? process.env.PR_NUMBER ?? "", + 10 + ); + if (Number.isInteger(maybePRNumber)) { + prNumber = maybePRNumber; + } + } catch (e) { + throw new Error(`Failed to parse GitHub event: ${e}`); + } + const refName = process.env.GITHUB_REF_NAME || null; + const sha = process.env.GITHUB_SHA || null; + cachedContext = { + provider: "github", + host, + owner, + repo, + urls: { api: apiURL, run: runURL }, + names: { ci: "GitHub Actions", pr: "PR", provider: "GitHub" }, + defaultBranch, + prNumber, + refName, + sha + }; + logger.debug("GitHub context", cachedContext); + return cachedContext; +} + +// src/compat/github/api.ts +var GitHubClient = class { + client; + constructor(token) { + this.client = createClient({ + authToken: token, + baseURL: getGitHubContext().urls.api, + owner: getGitHubContext().owner, + repo: getGitHubContext().repo, + resources: [BaseCommits, BaseComments2, BasePulls], + logLevel: "warn", + logger + }); + } + async listComments(prNumber) { + const { data } = await this.client.repos.issues.comments.list(prNumber); + return data.map((c) => ({ id: c.id, body: c.body ?? "" })); + } + async createComment(prNumber, props) { + const data = await this.client.repos.issues.comments.create( + prNumber, + props + ); + return { id: data.id, body: data.body }; + } + async updateComment(_prNumber, { id, body }) { + const data = await this.client.repos.issues.comments.update(id, { + body + }); + return { id: data.id, body: data.body }; + } + async getPullRequest(number) { + const data = await this.client.repos.pulls.retrieve(number); + return { + number, + state: data.merged_at ? "merged" : data.state, + title: data.title, + base_sha: data.base.sha, + base_ref: data.base.ref, + head_ref: data.head.ref, + head_sha: data.head.sha, + merge_commit_sha: data.merge_commit_sha + }; + } + async getPullRequestForCommit(sha) { + const pullRequests = await this.client.repos.commits.listPullRequests(sha).then( + ({ data }) => data.filter((c) => c.merged_at || c.state !== "closed") + ).catch((err) => { + if (err instanceof APIError2 && (err.status === 401 || err.status === 403 || err.status === 404)) { + return []; } - loggerFor2(this).info(responseInfo); - loggerFor2(this).debug(`[${requestLogID}] response start`, formatRequestDetails2({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - durationMs: headersTime - startTime - })); - return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; + throw err; + }); + if (pullRequests.length === 0) { + return null; } - async fetchWithTimeout(url, init, ms, controller) { - const { signal, method, ...options } = init || {}; - const abort = this._makeAbort(controller); - if (signal) - signal.addEventListener("abort", abort, { once: true }); - const timeout = setTimeout(abort, ms); - const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body; - const fetchOptions = { - signal: controller.signal, - ...isReadableBody ? { duplex: "half" } : {}, - method: "GET", - ...options - }; - if (method) { - fetchOptions.method = method.toUpperCase(); - } - try { - return await this.fetch.call(void 0, url, fetchOptions); - } finally { - clearTimeout(timeout); + if (pullRequests.length > 1) { + logger.warn( + `Multiple pull requests found for commit; only using first.`, + { commit: sha, pulls: pullRequests.map((c) => c.number) } + ); + } + const pull = pullRequests[0]; + return { + number: pull.number, + state: pull.merged_at ? "merged" : pull.state, + title: pull.title, + base_sha: pull.base.sha, + base_ref: pull.base.ref, + head_ref: pull.head.ref, + head_sha: pull.head.sha, + merge_commit_sha: pull.merge_commit_sha + }; + } +}; +var cachedClient; +function getGitHubClient() { + if (cachedClient !== void 0) { + return cachedClient; + } + const token = getInput("github_token"); + if (token) { + cachedClient = new GitHubClient(token); + } else { + logger.info("No GitHub token found via input 'github_token'."); + cachedClient = null; + } + return cachedClient; +} + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/errors.mjs +function isAbortError3(err) { + return typeof err === "object" && err !== null && // Spec-compliant fetch implementations + ("name" in err && err.name === "AbortError" || // Expo fetch + "message" in err && String(err.message).includes("FetchRequestCanceledException")); +} +var castToError3 = (err) => { + if (err instanceof Error) + return err; + if (typeof err === "object" && err !== null) { + try { + if (Object.prototype.toString.call(err) === "[object Error]") { + const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); + if (err.stack) + error.stack = err.stack; + if (err.cause && !error.cause) + error.cause = err.cause; + if (err.name) + error.name = err.name; + return error; } + } catch { } - async shouldRetry(response) { - const shouldRetryHeader = response.headers.get("x-should-retry"); - if (shouldRetryHeader === "true") - return true; - if (shouldRetryHeader === "false") - return false; - if (response.status === 408) - return true; - if (response.status === 409) - return true; - if (response.status === 429) - return true; - if (response.status >= 500) - return true; - return false; + try { + return new Error(JSON.stringify(err)); + } catch { } - async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { - let timeoutMillis; - const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms"); - if (retryAfterMillisHeader) { - const timeoutMs = parseFloat(retryAfterMillisHeader); - if (!Number.isNaN(timeoutMs)) { - timeoutMillis = timeoutMs; - } - } - const retryAfterHeader = responseHeaders?.get("retry-after"); - if (retryAfterHeader && !timeoutMillis) { - const timeoutSeconds = parseFloat(retryAfterHeader); - if (!Number.isNaN(timeoutSeconds)) { - timeoutMillis = timeoutSeconds * 1e3; - } else { - timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); - } - } - if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1e3)) { - const maxRetries = options.maxRetries ?? this.maxRetries; - timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); - } - await sleep2(timeoutMillis); - return this.makeRequest(options, retriesRemaining - 1, requestLogID); + } + return new Error(err); +}; + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/core/error.mjs +var GitLabError = /* @__PURE__ */ (() => { + class GitLabError2 extends Error { + } + return GitLabError2; +})(); +var APIError3 = class _APIError extends GitLabError { + constructor(status, error, message, headers) { + super(`${_APIError.makeMessage(status, error, message)}`); + this.status = status; + this.headers = headers; + this.error = error; + } + static makeMessage(status, error, message) { + const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message; + if (status && msg) { + return `${status} ${msg}`; } - calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { - const initialRetryDelay = 0.5; - const maxRetryDelay = 8; - const numRetries = maxRetries - retriesRemaining; - const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); - const jitter = 1 - Math.random() * 0.25; - return sleepSeconds * jitter * 1e3; + if (status) { + return `${status} status code (no body)`; } - async buildRequest(inputOptions, { retryCount = 0 } = {}) { - const options = { ...inputOptions }; - const { method, path: path7, query, defaultBaseURL } = options; - const url = this.buildURL(path7, query, defaultBaseURL); - if ("timeout" in options) - validatePositiveInteger2("timeout", options.timeout); - options.timeout = options.timeout ?? this.timeout; - const { bodyHeaders, body } = this.buildBody({ options }); - const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); - const req = { - method, - headers: reqHeaders, - ...options.signal && { signal: options.signal }, - ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" }, - ...body && { body }, - ...this.fetchOptions ?? {}, - ...options.fetchOptions ?? {} - }; - return { req, url, timeout: options.timeout }; + if (msg) { + return msg; } - async buildHeaders({ options, method, bodyHeaders, retryCount }) { - let idempotencyHeaders = {}; - if (this.idempotencyHeader && method !== "get") { - if (!options.idempotencyKey) - options.idempotencyKey = this.defaultIdempotencyKey(); - idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; - } - const headers = buildHeaders2([ - idempotencyHeaders, - { - Accept: "application/json", - "User-Agent": this.getUserAgent(), - "X-Stainless-Retry-Count": String(retryCount), - ...options.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options.timeout / 1e3)) } : {}, - ...getPlatformHeaders2() - }, - await this.authHeaders(options), - this._options.defaultHeaders, - bodyHeaders, - options.headers - ]); - this.validateHeaders(headers); - return headers.values; + return "(no status code or body)"; + } + static generate(status, errorResponse, message, headers) { + if (!status || !headers) { + return new APIConnectionError3({ message, cause: castToError3(errorResponse) }); } - _makeAbort(controller) { - return () => controller.abort(); + const error = errorResponse; + if (status === 400) { + return new BadRequestError3(status, error, message, headers); } - buildBody({ options: { body, headers: rawHeaders } }) { - if (!body) { - return { bodyHeaders: void 0, body: void 0 }; - } - const headers = buildHeaders2([rawHeaders]); - if ( - // Pass raw type verbatim - ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && // Preserve legacy string encoding behavior for now - headers.values.has("content-type") || // `Blob` is superset of `File` - globalThis.Blob && body instanceof globalThis.Blob || // `FormData` -> `multipart/form-data` - body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded` - body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`) - globalThis.ReadableStream && body instanceof globalThis.ReadableStream - ) { - return { bodyHeaders: void 0, body }; - } else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) { - return { bodyHeaders: void 0, body: ReadableStreamFrom2(body) }; - } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") { - return { - bodyHeaders: { "content-type": "application/x-www-form-urlencoded" }, - body: this.stringifyQuery(body) - }; - } else { - return __classPrivateFieldGet2(this, _BaseGitLab_encoder, "f").call(this, { body, headers }); - } + if (status === 401) { + return new AuthenticationError3(status, error, message, headers); + } + if (status === 403) { + return new PermissionDeniedError3(status, error, message, headers); + } + if (status === 404) { + return new NotFoundError3(status, error, message, headers); + } + if (status === 409) { + return new ConflictError3(status, error, message, headers); } - } - _BaseGitLab_encoder = /* @__PURE__ */ new WeakMap(), _BaseGitLab_instances = /* @__PURE__ */ new WeakSet(), _BaseGitLab_baseURLOverridden = function _BaseGitLab_baseURLOverridden2() { - return this.baseURL !== "https://gitlab.com/api/v4"; - }; - BaseGitLab2.DEFAULT_TIMEOUT = 6e4; - return BaseGitLab2; -})(); - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/tree-shakable.mjs -function createClient2(options) { - const client = new BaseGitLab(options); - for (const ResourceClass of options.resources) { - const resourceInstance = new ResourceClass(client); - let object = client; - for (const part of ResourceClass._key.slice(0, -1)) { - if (hasOwn2(object, part)) { - object = object[part]; - } else { - Object.defineProperty(object, part, { - value: object = {}, - configurable: true, - enumerable: true, - writable: true - }); - } + if (status === 422) { + return new UnprocessableEntityError3(status, error, message, headers); } - const name = ResourceClass._key.at(-1); - if (!hasOwn2(object, name)) { - Object.defineProperty(object, name, { - value: resourceInstance, - configurable: true, - enumerable: true, - writable: true - }); - } else { - if (object[name] instanceof APIResource2) { - throw new TypeError(`Resource at ${ResourceClass._key.join(".")} already exists!`); - } else { - object[name] = Object.assign(resourceInstance, object[name]); - } + if (status === 429) { + return new RateLimitError3(status, error, message, headers); + } + if (status >= 500) { + return new InternalServerError3(status, error, message, headers); } + return new _APIError(status, error, message, headers); } - return client; -} - -// src/compat/gitlab/context.ts -var cachedContext2; -function getGitLabContext() { - if (cachedContext2) { - return cachedContext2; +}; +var APIUserAbortError3 = class extends APIError3 { + constructor({ message } = {}) { + super(void 0, void 0, message || "Request was aborted.", void 0); } - const owner = process.env.CI_PROJECT_NAMESPACE; - const repo = process.env.CI_PROJECT_NAME; - const runURL = process.env.CI_JOB_URL; - const projectID = process.env.CI_PROJECT_ID; - if (!owner || !repo || !runURL || !projectID) { - throw new Error( - "Expected env vars CI_PROJECT_NAMESPACE, CI_PROJECT_NAME, CI_JOB_URL, and CI_PROJECT_ID to be set." - ); +}; +var APIConnectionError3 = class extends APIError3 { + constructor({ message, cause }) { + super(void 0, void 0, message || "Connection error.", void 0); + if (cause) + this.cause = cause; } - const host = process.env.CI_SERVER_URL || "https://gitlab.com"; - const apiURL = process.env.CI_API_V4_URL || `${host}/api/v4`; - const maybePRNumber = parseInt( - process.env.CI_MERGE_REQUEST_IID || process.env.MR_NUMBER || "", - 10 - ); - const defaultBranch = process.env.CI_DEFAULT_BRANCH || null; - const prNumber = Number.isInteger(maybePRNumber) ? maybePRNumber : null; - const refName = process.env.CI_COMMIT_REF_NAME || null; - const sha = process.env.CI_COMMIT_SHA || null; - cachedContext2 = { - provider: "gitlab", - host, - owner, - repo, - urls: { api: apiURL, run: runURL }, - names: { ci: "GitLab CI", pr: "MR", provider: "GitLab" }, - defaultBranch, - prNumber, - projectID, - refName, - sha - }; - logger.debug("GitLab context", cachedContext2); - return cachedContext2; -} +}; +var APIConnectionTimeoutError3 = class extends APIConnectionError3 { + constructor({ message } = {}) { + super({ message: message ?? "Request timed out." }); + } +}; +var BadRequestError3 = class extends APIError3 { +}; +var AuthenticationError3 = class extends APIError3 { +}; +var PermissionDeniedError3 = class extends APIError3 { +}; +var NotFoundError3 = class extends APIError3 { +}; +var ConflictError3 = class extends APIError3 { +}; +var UnprocessableEntityError3 = class extends APIError3 { +}; +var RateLimitError3 = class extends APIError3 { +}; +var InternalServerError3 = class extends APIError3 { +}; -// src/compat/gitlab/api.ts -var GitLabClient = class { - client; - constructor(token) { - this.client = createClient2({ - apiToken: token, - baseURL: getGitLabContext().urls.api, - resources: [BaseCommits3, BaseMergeRequests, BaseNotes2], - logLevel: "warn", - logger - }); +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/core/resource.mjs +var APIResource3 = /* @__PURE__ */ (() => { + class APIResource4 { + constructor(client) { + this._client = client; + } } - async listComments(prNumber) { - const comments = await this.client.projects.mergeRequests.notes.list(prNumber, { id: getGitLabContext().projectID }).then((data) => Array.isArray(data) ? data : [data]).catch((err) => { - if (err instanceof APIError2 && err.status === 404) { - return []; - } - throw err; - }); - return comments.map((c) => ({ id: c.id, body: c.body ?? "" })); + APIResource4._key = []; + return APIResource4; +})(); + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/utils/values.mjs +var startsWithSchemeRegexp3 = /^[a-z][a-z0-9+.-]*:/i; +var isAbsoluteURL3 = (url) => { + return startsWithSchemeRegexp3.test(url); +}; +var isArray3 = (val) => (isArray3 = Array.isArray, isArray3(val)); +var isReadonlyArray3 = isArray3; +function isEmptyObj3(obj) { + if (!obj) + return true; + for (const _k in obj) + return false; + return true; +} +function hasOwn3(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +var validatePositiveInteger3 = (name, n) => { + if (typeof n !== "number" || !Number.isInteger(n)) { + throw new GitLabError(`${name} must be an integer`); } - async createComment(prNumber, props) { - const data = await this.client.projects.mergeRequests.notes.create( - prNumber, - { ...props, id: getGitLabContext().projectID } - ); - return { id: data.id, body: data.body }; + if (n < 0) { + throw new GitLabError(`${name} must be a positive integer`); } - async updateComment(prNumber, props) { - const data = await this.client.projects.mergeRequests.notes.update( - props.id, - { ...props, id: getGitLabContext().projectID, noteable_id: prNumber } - ); - return { id: data.id, body: data.body }; + return n; +}; +var safeJSON3 = (text) => { + try { + return JSON.parse(text); + } catch (err) { + return void 0; } - async getPullRequest(number) { - let mergeRequest = null; - let attempts = 0; - while (attempts++ < 3) { - mergeRequest = await this.client.projects.mergeRequests.retrieve(number, { - id: getGitLabContext().projectID - }); - if (mergeRequest?.diff_refs?.start_sha && mergeRequest?.diff_refs?.head_sha) { - return { - number: mergeRequest.iid, - state: mergeRequest.state === "opened" ? "open" : mergeRequest.state === "locked" ? "closed" : mergeRequest.state, - title: mergeRequest.title, - base_sha: mergeRequest.diff_refs.start_sha, - base_ref: mergeRequest.target_branch, - head_sha: mergeRequest.diff_refs.head_sha, - head_ref: mergeRequest.source_branch, - merge_commit_sha: mergeRequest.merge_commit_sha || mergeRequest.squash_commit_sha || null - }; - } - await new Promise((resolve) => { - setTimeout(() => resolve(), 1e3 * (2 ** attempts + Math.random())); - }); +}; + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/headers.mjs +var brand_privateNullableHeaders3 = /* @__PURE__ */ Symbol("brand.privateNullableHeaders"); +function* iterateHeaders3(headers) { + if (!headers) + return; + if (brand_privateNullableHeaders3 in headers) { + const { values, nulls } = headers; + yield* values.entries(); + for (const name of nulls) { + yield [name, null]; } - logger.warn( - `Failed to find get diff_refs for merge request after ${attempts} attempts`, - { mergeRequestIID: number } - ); - return null; + return; } - async getPullRequestForCommit(sha) { - const mergeRequests = await this.client.projects.repository.commits.retrieveMergeRequests(sha, { - id: getGitLabContext().projectID - }).then( - (data) => ( - // The OAS claims it's a single object, but the docs claim it's an - // array? Just handle both. - (Array.isArray(data) ? data : [data]).filter( - (c) => c.state !== "closed" && c.state !== "locked" - ) - ) - ).catch((err) => { - if (err instanceof APIError2 && (err.status === 401 || err.status === 403 || err.status === 404)) { - return []; + let shouldClear = false; + let iter; + if (headers instanceof Headers) { + iter = headers.entries(); + } else if (isReadonlyArray3(headers)) { + iter = headers; + } else { + shouldClear = true; + iter = Object.entries(headers ?? {}); + } + for (let row of iter) { + const name = row[0]; + if (typeof name !== "string") + throw new TypeError("expected header name to be a string"); + const values = isReadonlyArray3(row[1]) ? row[1] : [row[1]]; + let didClear = false; + for (const value of values) { + if (value === void 0) + continue; + if (shouldClear && !didClear) { + didClear = true; + yield [name, null]; } - throw err; - }); - if (mergeRequests.length === 0) { - return null; + yield [name, value]; } - if (mergeRequests.length > 1) { - logger.warn( - `Multiple merge requests found for commit; only using first.`, - { commit: sha, mergeRequests: mergeRequests.map((c) => c.iid) } - ); + } +} +var buildHeaders3 = (newHeaders) => { + const targetHeaders = new Headers(); + const nullHeaders = /* @__PURE__ */ new Set(); + for (const headers of newHeaders) { + const seenHeaders = /* @__PURE__ */ new Set(); + for (const [name, value] of iterateHeaders3(headers)) { + const lowerName = name.toLowerCase(); + if (!seenHeaders.has(lowerName)) { + targetHeaders.delete(name); + seenHeaders.add(lowerName); + } + if (value === null) { + targetHeaders.delete(name); + nullHeaders.add(lowerName); + } else { + targetHeaders.append(name, value); + nullHeaders.delete(lowerName); + } } - const mergeRequestIID = mergeRequests[0].iid; - const mergeRequest = await this.getPullRequest(mergeRequestIID); - return mergeRequest; } + return { [brand_privateNullableHeaders3]: true, values: targetHeaders, nulls: nullHeaders }; }; -var cachedClient2; -function getGitLabClient() { - if (cachedClient2 !== void 0) { - return cachedClient2; - } - const token = getInput("GITLAB_TOKEN"); - if (token?.startsWith("$")) { - throw new Error( - `Input GITLAB_TOKEN starts with '$'; expected token to start with 'gl'. Does the CI have access to the variable?` - ); + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/utils/path.mjs +function encodeURIPath3(str) { + return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); +} +var EMPTY3 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); +var createPathTagFunction3 = (pathEncoder = encodeURIPath3) => function path7(statics, ...params) { + if (statics.length === 1) + return statics[0]; + let postPath = false; + const invalidSegments = []; + const path8 = statics.reduce((previousValue, currentValue, index) => { + if (/[?#]/.test(currentValue)) { + postPath = true; + } + const value = params[index]; + let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value); + if (index !== params.length && (value == null || typeof value === "object" && // handle values from other realms + value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY3) ?? EMPTY3)?.toString)) { + encoded = value + ""; + invalidSegments.push({ + start: previousValue.length + currentValue.length, + length: encoded.length, + error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter` + }); + } + return previousValue + currentValue + (index === params.length ? "" : encoded); + }, ""); + const pathOnly = path8.split(/[?#]/, 1)[0]; + const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; + let match; + while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) { + invalidSegments.push({ + start: match.index, + length: match[0].length, + error: `Value "${match[0]}" can't be safely passed as a path parameter` + }); } - if (token) { - cachedClient2 = new GitLabClient(token); - } else { - logger.info("No GitLab token found in input 'GITLAB_TOKEN'."); - cachedClient2 = null; + invalidSegments.sort((a, b) => a.start - b.start); + if (invalidSegments.length > 0) { + let lastEnd = 0; + const underline = invalidSegments.reduce((acc, segment) => { + const spaces = " ".repeat(segment.start - lastEnd); + const arrows = "^".repeat(segment.length); + lastEnd = segment.start + segment.length; + return acc + spaces + arrows; + }, ""); + throw new GitLabError(`Path parameters result in path with invalid segments: +${invalidSegments.map((e) => e.error).join("\n")} +${path8} +${underline}`); } - return cachedClient2; -} + return path8; +}; +var path3 = /* @__PURE__ */ createPathTagFunction3(encodeURIPath3); -// src/compat/api.ts -function api(options) { - let client; - switch (getProvider()) { - case "github": { - client = getGitHubClient(); - break; +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/resources/projects/merge-requests/notes/notes.mjs +var BaseNotes2 = /* @__PURE__ */ (() => { + class BaseNotes13 extends APIResource3 { + /** + * Create a new merge request note + * + * @example + * ```ts + * const apiEntitiesNote = + * await client.projects.mergeRequests.notes.create(0, { + * id: 'id', + * body: 'body', + * }); + * ``` + */ + create(noteableID, params, options) { + const { id, ...body } = params; + return this._client.post(path3`/projects/${id}/merge_requests/${noteableID}/notes`, { body, ...options }); } - case "gitlab": { - client = getGitLabClient(); - break; + /** + * Get a single merge request note + * + * @example + * ```ts + * const apiEntitiesNote = + * await client.projects.mergeRequests.notes.retrieve(0, { + * id: 'id', + * noteable_id: 0, + * }); + * ``` + */ + retrieve(noteID, params, options) { + const { id, noteable_id } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${noteable_id}/notes/${noteID}`, options); + } + /** + * Update an existing merge request note + * + * @example + * ```ts + * const apiEntitiesNote = + * await client.projects.mergeRequests.notes.update(0, { + * id: 'id', + * noteable_id: 0, + * }); + * ``` + */ + update(noteID, params, options) { + const { id, noteable_id, ...body } = params; + return this._client.put(path3`/projects/${id}/merge_requests/${noteable_id}/notes/${noteID}`, { + body, + ...options + }); + } + /** + * Get a list of merge request notes + * + * @example + * ```ts + * const apiEntitiesNote = + * await client.projects.mergeRequests.notes.list(0, { + * id: 'id', + * }); + * ``` + */ + list(noteableID, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${noteableID}/notes`, { query, ...options }); + } + /** + * Delete a merge request note + * + * @example + * ```ts + * const apiEntitiesNote = + * await client.projects.mergeRequests.notes.delete(0, { + * id: 'id', + * noteable_id: 0, + * }); + * ``` + */ + delete(noteID, params, options) { + const { id, noteable_id } = params; + return this._client.delete(path3`/projects/${id}/merge_requests/${noteable_id}/notes/${noteID}`, options); } } - if (!client) { - if (options?.optional) { - return null; - } else { - throw new Error("Failed to get API client."); + BaseNotes13._key = Object.freeze([ + "projects", + "mergeRequests", + "notes" + ]); + return BaseNotes13; +})(); + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/resources/projects/merge-requests/merge-requests.mjs +var BaseMergeRequests = /* @__PURE__ */ (() => { + class BaseMergeRequests3 extends APIResource3 { + /** + * Create a new merge request. + * + * @example + * ```ts + * const apiEntitiesMergeRequest = + * await client.projects.mergeRequests.create('string', { + * source_branch: 'source_branch', + * target_branch: 'target_branch', + * title: 'title', + * }); + * ``` + */ + create(id, body, options) { + return this._client.post(path3`/projects/${id}/merge_requests`, { body, ...options }); + } + /** + * Shows information about a single merge request. Note: the `changes_count` value + * in the response is a string, not an integer. This is because when an merge + * request has too many changes to display and store, it is capped at 1,000. In + * that case, the API returns the string `"1000+"` for the changes count. + * + * @example + * ```ts + * const apiEntitiesMergeRequest = + * await client.projects.mergeRequests.retrieve(0, { + * id: 'string', + * }); + * ``` + */ + retrieve(mergeRequestIid, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${mergeRequestIid}`, { query, ...options }); + } + /** + * Updates an existing merge request. You can change the target branch, title, or + * even close the merge request. + * + * @example + * ```ts + * const apiEntitiesMergeRequest = + * await client.projects.mergeRequests.update(0, { + * id: 'string', + * }); + * ``` + */ + update(mergeRequestIid, params, options) { + const { id, ...body } = params; + return this._client.put(path3`/projects/${id}/merge_requests/${mergeRequestIid}`, { body, ...options }); } - } - return client; -} - -// src/compat/context.ts -function ctx() { - switch (getProvider()) { - case "github": { - return getGitHubContext(); + /** + * Get all merge requests for this project. + * + * @example + * ```ts + * const apiEntitiesMergeRequestBasics = + * await client.projects.mergeRequests.list('string'); + * ``` + */ + list(id, query = {}, options) { + return this._client.get(path3`/projects/${id}/merge_requests`, { query, ...options }); } - case "gitlab": { - return getGitLabContext(); + /** + * Only for administrators and project owners. Deletes the merge request in + * question. + * + * @example + * ```ts + * await client.projects.mergeRequests.delete(0, { + * id: 'string', + * }); + * ``` + */ + delete(mergeRequestIid, params, options) { + const { id } = params; + return this._client.delete(path3`/projects/${id}/merge_requests/${mergeRequestIid}`, { + ...options, + headers: buildHeaders3([{ Accept: "*/*" }, options?.headers]) + }); } - } -} - -// src/compat/output.ts -var crypto = __toESM(require("node:crypto")); -var fs2 = __toESM(require("node:fs")); -function setOutput(name, value) { - if (getProvider() === "gitlab") return; - const stringified = value === null || value === void 0 ? "" : typeof value === "string" ? value : JSON.stringify(value); - const filePath = process.env["GITHUB_OUTPUT"]; - if (filePath && fs2.existsSync(filePath)) { - const delimiter = `ghadelimiter_${crypto.randomUUID()}`; - fs2.appendFileSync( - filePath, - `${name}<<${delimiter} -${stringified} -${delimiter} -`, - "utf-8" - ); - } else { - process.stdout.write(` -::set-output name=${name}::${stringified} -`); - } -} - -// src/compat/index.ts -async function getStainlessAuth() { - const apiKey = getInput("stainless_api_key", { - required: getProvider() === "gitlab" - }); - if (apiKey) { - logger.debug("Authenticating with provided Stainless API key"); - return { - key: apiKey, - expiresAt: null - }; - } - logger.debug("Authenticating with GitHub OIDC"); - const requestUrl = process.env.ACTIONS_ID_TOKEN_REQUEST_URL; - const requestToken = process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN; - if (!requestUrl || !requestToken) { - throw new Error( - `Failed to authenticate with GitHub OIDC. Make sure your workflow has 'id-token: write' permission and that you have the Stainless GitHub App installed: https://www.stainless.com/docs/guides/publish/#install-the-stainless-github-app` - ); - } - try { - const response = await fetch(`${requestUrl}&audience=api.stainless.com`, { - headers: { Authorization: `Bearer ${requestToken}` } - }); - if (!response.ok) { - throw new Error(`HTTP ${response.status}: ${await response.text()}`); + /** + * Adds spent time for this merge_request. + * + * @example + * ```ts + * const apiEntitiesIssuableTimeStats = + * await client.projects.mergeRequests.addSpentTime(0, { + * id: 'string', + * duration: 'duration', + * }); + * ``` + */ + addSpentTime(mergeRequestIid, params, options) { + const { id, ...body } = params; + return this._client.post(path3`/projects/${id}/merge_requests/${mergeRequestIid}/add_spent_time`, { + body, + ...options + }); } - const data = await response.json(); - if (!data.value) { - throw new Error("No token in OIDC response"); + /** + * Approve a merge request + * + * @example + * ```ts + * const apiEntitiesMergeRequestApprovals = + * await client.projects.mergeRequests.approve(0, { + * id: 'id', + * }); + * ``` + */ + approve(mergeRequestIid, params, options) { + const { id, ...body } = params; + return this._client.post(path3`/projects/${id}/merge_requests/${mergeRequestIid}/approve`, { + body, + ...options + }); } - return { - key: data.value, - expiresAt: Date.now() + 300 * 1e3 - }; - } catch (error) { - throw new Error( - `Failed to authenticate with GitHub OIDC. Make sure your workflow has 'id-token: write' permission and that you have the Stainless GitHub App installed: https://www.stainless.com/docs/guides/publish/#install-the-stainless-github-app. Error: ${error}` - ); - } -} - -// src/merge.run.ts -var fs5 = __toESM(require("node:fs")); - -// src/commitMessage.ts -var CONVENTIONAL_COMMIT_REGEX = new RegExp( - /^(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test)(\(.*\))?(!?): .*$/m -); -function makeCommitMessageConventional(message) { - if (message && !CONVENTIONAL_COMMIT_REGEX.test(message)) { - logger.warn( - `Commit message "${message}" is not in Conventional Commits format: https://www.conventionalcommits.org/en/v1.0.0/. Prepending "feat:" and using anyway.` - ); - return `feat: ${message}`; - } - return message; -} - -// src/markdown.ts -var import_ts_dedent = __toESM(require_dist()); -var Symbol2 = { - Bulb: "\u{1F4A1}", - Construction: "\u{1F6A7}", - Exclamation: "\u2757", - Eyes: "\u{1F440}", - GreenSquare: "\u{1F7E9}", - HeavyAsterisk: "\u2731", - HourglassFlowingSand: "\u23F3", - MiddleDot: "\xB7", - RedSquare: "\u{1F7E5}", - RightwardsArrow: "\u2192", - Skipped: "\u23ED\uFE0F", - SpeechBalloon: "\u{1F4AC}", - Warning: "\u26A0\uFE0F", - WhiteCheckMark: "\u2705", - WhiteLargeSquare: "\u2B1C", - Zap: "\u26A1" -}; -var Bold = (content) => `${content}`; -var CodeInline = (content) => `${content}`; -var Comment = (content) => ``; -var Italic = (content) => `${content}`; -function Dedent(templ, ...args) { - return (0, import_ts_dedent.dedent)(templ, ...args).trim().replaceAll(/\n\s*\n/gi, "\n\n"); -} -var Blockquote = (content) => Dedent` -
- - ${content} - -
- `; -var CodeBlock = (props) => { - const delimiter = "```"; - const content = typeof props === "string" ? props : props.content; - const language = typeof props === "string" ? "" : props.language; - return Dedent` - ${delimiter}${language} - ${content} - ${delimiter} - `; -}; -var Details = ({ - summary, - body, - indent = true, - open = false -}) => { - return Dedent` - - ${summary} - - ${indent ? Blockquote(body) : body} - - - `; -}; -var Heading = (content) => `

${content}

`; -var Link = ({ text, href }) => `${text}`; -var Rule = () => `
`; - -// src/outcomes.ts -var ASSUME_PENDING_CHECKS_SKIPPED_AFTER_SECS = 60; -var FailRunOn = [ - "never", - "fatal", - "error", - "warning", - "note" -]; -var OutcomeConclusion = [...FailRunOn, "success"]; -function shouldFailRun({ - failRunOn, - outcomes, - baseOutcomes -}) { - const failures = Object.entries(outcomes).flatMap(([language, outcome]) => { - const categorized = categorizeOutcome({ - outcome, - baseOutcome: baseOutcomes?.[language] - }); - if (categorized.isPending) { - return []; + /** + * Cancel merge if "Merge When Pipeline Succeeds" is enabled + * + * @example + * ```ts + * const apiEntitiesMergeRequest = + * await client.projects.mergeRequests.cancelMergeWhenPipelineSucceeds( + * 0, + * { id: 'string' }, + * ); + * ``` + */ + cancelMergeWhenPipelineSucceeds(mergeRequestIid, params, options) { + const { id } = params; + return this._client.post(path3`/projects/${id}/merge_requests/${mergeRequestIid}/cancel_merge_when_pipeline_succeeds`, options); } - const { severity, isRegression, description } = categorized; - const didFail = isRegression !== false && severity && OutcomeConclusion.indexOf(severity) <= OutcomeConclusion.indexOf(failRunOn); - return didFail ? [ - { - language, - reason: getReason({ - description, - isRegression - }) - } - ] : []; - }); - if (failures.length > 0) { - logger.warn("The following languages did not build successfully:"); - for (const { language, reason } of failures) { - logger.warn(` ${language}: ${reason}`); + /** + * Resets the total spent time for this merge_request to 0 seconds. + * + * @example + * ```ts + * const apiEntitiesIssuableTimeStats = + * await client.projects.mergeRequests.resetSpentTime(0, { + * id: 'string', + * }); + * ``` + */ + resetSpentTime(mergeRequestIid, params, options) { + const { id } = params; + return this._client.post(path3`/projects/${id}/merge_requests/${mergeRequestIid}/reset_spent_time`, options); } - return false; - } - return true; -} -function categorizeOutcome({ - outcome, - baseOutcome -}) { - const baseConclusion = baseOutcome?.commit?.conclusion; - const headConclusion = outcome.commit?.conclusion; - if (!headConclusion || baseOutcome && !baseConclusion) { - return { isPending: true }; - } - const baseChecks = baseOutcome && baseOutcome.commit?.commit ? getChecks(baseOutcome) : {}; - const headChecks = outcome.commit?.commit ? getChecks(outcome) : {}; - if ([...Object.values(headChecks), ...Object.values(baseChecks)].some( - (check) => check && check.status !== "completed" - )) { - return { isPending: true }; - } - const newDiagnostics = sortDiagnostics( - baseOutcome ? getNewDiagnostics(outcome.diagnostics, baseOutcome.diagnostics) : outcome.diagnostics - ); - const conclusions = { - fatal: [ - "fatal", - "payment_required", - "timed_out", - "upstream_merge_conflict", - "version_bump" - ], - conflict: ["merge_conflict"], - diagnostic: ["error", "warning", "note"], - success: ["success", "noop", "cancelled"] - }; - const checks = getNewChecks(headChecks, baseChecks); - const checkFailures = CheckType.filter( - (checkType) => checks[checkType] && checks[checkType].status === "completed" && ["failure", "timed_out"].includes(checks[checkType].completed.conclusion) - ); - if (headConclusion === "timed_out" || baseConclusion === "timed_out") { - return { - isPending: false, - conclusion: "timed_out", - severity: "fatal", - description: "timed out before completion", - isRegression: null - }; - } - if (conclusions.fatal.includes(headConclusion)) { - return { - isPending: false, - conclusion: "fatal", - severity: "fatal", - description: `had a "${headConclusion}" conclusion, and no code was generated`, - isRegression: baseConclusion ? conclusions.fatal.includes(baseConclusion) ? false : true : null - }; - } - if (baseConclusion && conclusions.fatal.includes(baseConclusion)) { - return { - isPending: false, - conclusion: headConclusion, - severity: null, - description: `had a "${baseOutcome?.commit?.conclusion}" conclusion in the base build, which improved to "${headConclusion}"`, - isRegression: false - }; - } - if (conclusions.diagnostic.includes(headConclusion) || newDiagnostics.length > 0 || checkFailures.length > 0) { - const categoryOutcome = conclusions.diagnostic.includes(headConclusion) ? { - severity: headConclusion, - description: `had at least one "${headConclusion}" diagnostic`, - isRegression: baseConclusion ? conclusions.success.includes(baseConclusion) || conclusions.diagnostic.indexOf(headConclusion) < conclusions.diagnostic.indexOf(baseConclusion) ? true : false : null, - rank: 1 - } : null; - const diagnosticLevelOutcome = newDiagnostics.length > 0 ? { - severity: newDiagnostics[0].level, - description: `had at least one ${baseOutcome ? "new " : ""}${newDiagnostics[0].level} diagnostic`, - isRegression: baseOutcome ? true : null, - rank: 2 - } : null; - let checkFailureOutcome; - for (const { step, severity } of [ - { step: "build", severity: "error" }, - { step: "lint", severity: "warning" }, - { step: "test", severity: "warning" } - ]) { - if (checkFailures.includes(step)) { - checkFailureOutcome = { - severity, - description: `had a failure in the ${step} CI job`, - isRegression: baseChecks ? true : null, - rank: 3 - }; - break; - } + /** + * Resets the estimated time for this merge_request to 0 seconds. + * + * @example + * ```ts + * const apiEntitiesIssuableTimeStats = + * await client.projects.mergeRequests.resetTimeEstimate(0, { + * id: 'string', + * }); + * ``` + */ + resetTimeEstimate(mergeRequestIid, params, options) { + const { id } = params; + return this._client.post(path3`/projects/${id}/merge_requests/${mergeRequestIid}/reset_time_estimate`, options); } - const worstOutcome = [ - categoryOutcome, - diagnosticLevelOutcome, - checkFailureOutcome - ].filter((r) => r !== null).sort( - (a, b) => ( - // sort by regression status then severity then rank - (!(a.severity === "fatal" || b.severity === "fatal") ? [true, null, false].indexOf(a.isRegression) - [true, null, false].indexOf(b.isRegression) : 0) || conclusions.diagnostic.indexOf(a.severity) - conclusions.diagnostic.indexOf(b.severity) || a.rank - b.rank - ) - )[0]; - return { - isPending: false, - conclusion: worstOutcome.severity, - ...worstOutcome - }; - } - if (conclusions.conflict.includes(headConclusion)) { - return { - isPending: false, - conclusion: "merge_conflict", - severity: baseConclusion !== "merge_conflict" ? "warning" : null, - description: "resulted in a merge conflict between your custom code and the newly generated changes", - isRegression: baseConclusion ? baseConclusion !== "merge_conflict" ? true : false : null - }; - } - return { - isPending: false, - conclusion: headConclusion, - severity: null, - description: headConclusion === "success" ? "was successful" : `had a conclusion of ${headConclusion}`, - isRegression: null - }; -} -function getReason({ - description, - isRegression -}) { - return `Your SDK build ${description}${isRegression === true ? ", which is a regression from the base state" : isRegression === false ? ", but this did not represent a regression" : ""}.`; -} -var DiagnosticLevel = ["fatal", "error", "warning", "note"]; -function countDiagnosticLevels(diagnostics) { - return diagnostics.reduce( - (counts, diag) => { - counts[diag.level] = (counts[diag.level] || 0) + 1; - return counts; - }, - { - fatal: 0, - error: 0, - warning: 0, - note: 0 + /** + * List approval rules for merge request + * + * @example + * ```ts + * await client.projects.mergeRequests.retrieveApprovalSettings( + * 0, + * { id: 'string' }, + * ); + * ``` + */ + retrieveApprovalSettings(mergeRequestIid, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${mergeRequestIid}/approval_settings`, { + query, + ...options, + headers: buildHeaders3([{ Accept: "*/*" }, options?.headers]) + }); + } + /** + * Get approval state of merge request + * + * @example + * ```ts + * const response = + * await client.projects.mergeRequests.retrieveApprovalState( + * 0, + * { id: 'string' }, + * ); + * ``` + */ + retrieveApprovalState(mergeRequestIid, params, options) { + const { id } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${mergeRequestIid}/approval_state`, options); + } + /** + * Get all merge requests are blockees for this merge request + * + * @example + * ```ts + * const apiEntitiesMergeRequestDependency = + * await client.projects.mergeRequests.retrieveBlockees(0, { + * id: 'string', + * }); + * ``` + */ + retrieveBlockees(mergeRequestIid, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${mergeRequestIid}/blockees`, { + query, + ...options + }); + } + /** + * Shows information about the merge request including its files and changes. + * + * @example + * ```ts + * const response = + * await client.projects.mergeRequests.retrieveChanges(0, { + * id: 'string', + * }); + * ``` + */ + retrieveChanges(mergeRequestIid, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${mergeRequestIid}/changes`, { + query, + ...options + }); + } + /** + * Get all the issues that would be closed by merging the provided merge request. + * + * @example + * ```ts + * const response = + * await client.projects.mergeRequests.retrieveClosesIssues( + * 0, + * { id: 'string' }, + * ); + * ``` + */ + retrieveClosesIssues(mergeRequestIid, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${mergeRequestIid}/closes_issues`, { + query, + ...options + }); } - ); -} -function getNewDiagnostics(diagnostics, baseDiagnostics) { - if (!baseDiagnostics) { - return diagnostics; - } - return diagnostics.filter( - (d) => !baseDiagnostics.some( - (bd) => bd.code === d.code && bd.message === d.message && bd.config_ref === d.config_ref && bd.oas_ref === d.oas_ref - ) - ); -} -function sortDiagnostics(diagnostics) { - return diagnostics.sort( - (a, b) => DiagnosticLevel.indexOf(a.level) - DiagnosticLevel.indexOf(b.level) - ); -} -var CheckType = ["build", "lint", "test"]; -function getChecks(outcome) { - const results = {}; - const commitCompletedMoreThanXSecsAgo = outcome.commit ? (/* @__PURE__ */ new Date()).getTime() - new Date(outcome.commit.completed_at).getTime() > ASSUME_PENDING_CHECKS_SKIPPED_AFTER_SECS * 1e3 : false; - for (const checkType of CheckType) { - if (outcome[checkType]?.status === "not_started" && commitCompletedMoreThanXSecsAgo) { - outcome[checkType] = { - status: "completed", - conclusion: "skipped", - completed: { - conclusion: "skipped", - url: null - }, - url: null - }; + /** + * Get a list of merge request commits. + * + * @example + * ```ts + * const apiEntitiesCommit = + * await client.projects.mergeRequests.retrieveCommits(0, { + * id: 'string', + * }); + * ``` + */ + retrieveCommits(mergeRequestIid, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${mergeRequestIid}/commits`, { + query, + ...options + }); } - results[checkType] = outcome[checkType] || null; - } - return results; -} -function getNewChecks(headChecks, baseChecks) { - const result = {}; - for (const checkType of CheckType) { - const headCheck = headChecks[checkType]; - const baseCheck = baseChecks ? baseChecks[checkType] : null; - if (headCheck) { - const baseConclusion = baseCheck?.status === "completed" && baseCheck.conclusion; - const conclusion = headCheck.status === "completed" && headCheck.conclusion; - if (!baseConclusion || baseConclusion !== conclusion) { - result[checkType] = headCheck; - } + /** + * Get a list of merge request diffs. + * + * @example + * ```ts + * const apiEntitiesDiff = + * await client.projects.mergeRequests.retrieveDiffs(0, { + * id: 'string', + * }); + * ``` + */ + retrieveDiffs(mergeRequestIid, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${mergeRequestIid}/diffs`, { + query, + ...options + }); } - } - return result; -} - -// src/comment.ts -var COMMENT_TITLE = Heading( - `${Symbol2.HeavyAsterisk} Stainless preview builds` -); -var COMMENT_FOOTER_DIVIDER = Comment("stainless-preview-footer"); -function printComment({ - noChanges, - orgName, - projectName, - branch, - commitMessage, - targetCommitMessages, - pendingAiCommitMessages, - baseOutcomes, - outcomes -}) { - const Blocks4 = (() => { - if (noChanges) { - return "No changes were made to the SDKs."; + /** + * Returns the up to date merge-ref HEAD commit + * + * @example + * ```ts + * await client.projects.mergeRequests.retrieveMergeRef(0, { + * id: 'string', + * }); + * ``` + */ + retrieveMergeRef(mergeRequestIid, params, options) { + const { id } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${mergeRequestIid}/merge_ref`, { + ...options, + headers: buildHeaders3([{ Accept: "*/*" }, options?.headers]) + }); } - const canEdit = !!baseOutcomes; - return [ - Dedent` - This ${ctx().names.pr} will update the ${CodeInline( - projectName - )} SDKs with the following commit ${targetCommitMessages ? "messages" : "message"}. - `, - targetCommitMessages ? CommitMessagesSection({ - targets: Object.keys(outcomes).sort(), - pendingAiCommitMessages, - targetCommitMessages, - commitMessage - }) : CodeBlock(commitMessage), - !canEdit ? null : targetCommitMessages ? "Edit this comment to update them. They will appear in their respective SDK's changelogs." : "Edit this comment to update it. It will appear in the SDK's changelogs.", - Results({ orgName, projectName, branch, outcomes, baseOutcomes }) - ].filter((f) => f !== null).join(` - -`); - })(); - const dateString = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").replace(/\.\d+Z$/, " UTC"); - const fullComment = Dedent` - ${COMMENT_TITLE} - - ${Blocks4} - - ${Rule()} - - ${COMMENT_FOOTER_DIVIDER} - - ${Italic( - `This comment is auto-generated by ${ctx().names.ci} and is automatically kept up to date as you push.
If you push custom code to the preview branch, ${Link({ - text: `re-run this workflow`, - href: ctx().urls.run - })} to update the comment.
Last updated: ${dateString}` - )} - `; - return fullComment; -} -function CommitMessagesSection({ - targets, - pendingAiCommitMessages, - targetCommitMessages, - commitMessage -}) { - return targets.map((target) => { - const statusText = pendingAiCommitMessages?.has(target) ? `${Symbol2.HourglassFlowingSand} (generating...)` : ""; - const message = targetCommitMessages[target] ?? commitMessage; - return Dedent` - **${target}** - ${statusText}${CodeBlock(message)} - `; - }).join("\n"); -} -var DiagnosticIcon = { - fatal: Symbol2.Exclamation, - error: Symbol2.Exclamation, - warning: Symbol2.Warning, - note: Symbol2.Bulb -}; -function Results({ - orgName, - projectName, - branch, - outcomes, - baseOutcomes -}) { - const results = []; - let hasPending = false; - Object.entries(outcomes).forEach(([lang, head]) => { - const base = baseOutcomes?.[lang]; - hasPending ||= categorizeOutcome({ - outcome: head, - baseOutcome: base - }).isPending ?? false; - const result = Result({ - orgName, - projectName, - branch, - lang, - head, - base - }); - if (result) { - results.push(result); + /** + * Get a list of merge request participants. + * + * @example + * ```ts + * const apiEntitiesUserBasic = + * await client.projects.mergeRequests.retrieveParticipants( + * 0, + * { id: 'string' }, + * ); + * ``` + */ + retrieveParticipants(mergeRequestIid, params, options) { + const { id } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${mergeRequestIid}/participants`, options); + } + /** + * Get the raw diffs of a merge request that can used programmatically. + * + * @example + * ```ts + * await client.projects.mergeRequests.retrieveRawDiffs(0, { + * id: 'string', + * }); + * ``` + */ + retrieveRawDiffs(mergeRequestIid, params, options) { + const { id } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${mergeRequestIid}/raw_diffs`, { + ...options, + headers: buildHeaders3([{ Accept: "*/*" }, options?.headers]) + }); + } + /** + * Get all the related issues from title, description, commits, comments and + * discussions of the merge request. + * + * @example + * ```ts + * await client.projects.mergeRequests.retrieveRelatedIssues( + * 0, + * { id: 'string' }, + * ); + * ``` + */ + retrieveRelatedIssues(mergeRequestIid, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${mergeRequestIid}/related_issues`, { + query, + ...options, + headers: buildHeaders3([{ Accept: "*/*" }, options?.headers]) + }); } - }); - if (hasPending) { - results.push( - Dedent` - ${Symbol2.HourglassFlowingSand} These are partial results; builds are still running. - ` - ); - } - return results.join("\n\n"); -} -function Result({ - orgName, - projectName, - branch, - lang, - head, - base -}) { - const categorized = categorizeOutcome({ - outcome: head, - baseOutcome: base - }); - const { ResultIcon, Description } = (() => { - if (categorized.isPending) { - return { - ResultIcon: Symbol2.HourglassFlowingSand, - Description: "" - }; + /** + * Get a list of merge request reviewers. + * + * @example + * ```ts + * const response = + * await client.projects.mergeRequests.retrieveReviewers(0, { + * id: 'string', + * }); + * ``` + */ + retrieveReviewers(mergeRequestIid, params, options) { + const { id } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${mergeRequestIid}/reviewers`, options); } - const { severity, conclusion, isRegression, description } = categorized; - const reason = getReason({ - description, - isRegression - }); - if (isRegression !== false && severity === "fatal") { - return { - ResultIcon: Symbol2.Exclamation, - Description: Italic(reason) - }; + /** + * Get time tracking stats + * + * @example + * ```ts + * const apiEntitiesIssuableTimeStats = + * await client.projects.mergeRequests.retrieveTimeStats(0, { + * id: 'string', + * }); + * ``` + */ + retrieveTimeStats(mergeRequestIid, params, options) { + const { id } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${mergeRequestIid}/time_stats`, options); } - if (isRegression !== false && conclusion === "merge_conflict") { - return { - ResultIcon: Symbol2.Zap, - Description: [ - Italic(reason), - Italic( - `You don't need to resolve this conflict right now, but you will need to resolve it for your changes to be released to your users. Read more about why this happened ${Link({ - text: "here", - href: "https://www.stainless.com/docs/guides/add-custom-code" - })}.` - ) - ].join("\n") - }; + /** + * Set status of an external status check + * + * @example + * ```ts + * const response = + * await client.projects.mergeRequests.statusCheckResponses( + * 1, + * { + * id: '1', + * external_status_check_id: 1, + * sha: '5957a570eee0ac4580ec027fb874ad7514d1e576', + * status: 'passed', + * }, + * ); + * ``` + */ + statusCheckResponses(mergeRequestIid, params, options) { + const { id, ...body } = params; + return this._client.post(path3`/projects/${id}/merge_requests/${mergeRequestIid}/status_check_responses`, { + body, + ...options + }); } - if (isRegression !== false && severity !== "note" && severity !== null) { - return { - ResultIcon: Symbol2.Warning, - Description: Italic(reason) - }; + /** + * Subscribe to a resource + * + * @example + * ```ts + * const apiEntitiesMergeRequest = + * await client.projects.mergeRequests.subscribe( + * 'subscribable_id', + * { id: 'id' }, + * ); + * ``` + */ + subscribe(subscribableID, params, options) { + const { id } = params; + return this._client.post(path3`/projects/${id}/merge_requests/${subscribableID}/subscribe`, options); } - return { - ResultIcon: severity === "fatal" ? Symbol2.Construction : Symbol2.WhiteCheckMark, - Description: Italic(reason) - }; - })(); - return Details({ - summary: [ - ResultIcon, - Bold(`${projectName}-${lang}`), - [ - Link({ - text: "studio", - href: `https://app.stainless.com/${orgName}/${projectName}/studio?language=${lang}&branch=${encodeURIComponent(branch)}` - }), - GitHubLink(head), - base ? CompareLink(base, head) : null, - MergeConflictLink(head) - ].filter((link) => link !== null).join(` ${Symbol2.MiddleDot} `) - ].join(" "), - body: [ - Description, - StatusLine(base, head), - InstallationDetails(head, lang), - base ? DiagnosticsDetails(head, base) : null - ].filter((value) => Boolean(value)).join("\n"), - open: !categorized.isPending && categorized.isRegression !== false && categorized.severity !== "note" && categorized.severity !== null - }); -} -function StatusLine(base, head) { - return [ - StatusStep(base, head, "generate"), - StatusStep(base, head, "build"), - StatusStep(base, head, "lint"), - StatusStep(base, head, "test") - ].filter((value) => Boolean(value)).join(` ${Symbol2.RightwardsArrow} `); -} -function StatusStep(base, head, step) { - let baseStatus = base ? StatusSymbol(base, step) : null; - let headStatus = StatusSymbol(head, step); - if (!headStatus) { - return null; - } - if (baseStatus === Symbol2.HourglassFlowingSand || headStatus === Symbol2.HourglassFlowingSand) { - baseStatus = Symbol2.HourglassFlowingSand; - headStatus = Symbol2.HourglassFlowingSand; - } - const headText = CodeInline(`${step} ${headStatus}`); - const headURL = StatusURL(head, step); - const headLink = headURL ? Link({ text: headText, href: headURL }) : headText; - if (!baseStatus || baseStatus === headStatus) { - return headLink; - } - const baseText = CodeInline(`${step} ${baseStatus}`); - const baseURL = StatusURL(base, step); - const baseLink = baseURL ? Link({ text: baseText, href: baseURL }) : baseText; - return `${headLink} (prev: ${baseLink})`; -} -function StatusSymbol(outcome, step) { - if (!outcome.commit?.completed?.commit) { - return null; - } - if (step === "generate") { - switch (outcome.commit.completed.conclusion) { - case "fatal": - case "error": - case "cancelled": - return Symbol2.Exclamation; - case "merge_conflict": - return Symbol2.Zap; - case "upstream_merge_conflict": - case "warning": - return Symbol2.Warning; - default: - return Symbol2.WhiteCheckMark; + /** + * Sets an estimated time of work for this merge_request. + * + * @example + * ```ts + * const apiEntitiesIssuableTimeStats = + * await client.projects.mergeRequests.timeEstimate(0, { + * id: 'string', + * duration: '3h30m', + * }); + * ``` + */ + timeEstimate(mergeRequestIid, params, options) { + const { id, ...body } = params; + return this._client.post(path3`/projects/${id}/merge_requests/${mergeRequestIid}/time_estimate`, { + body, + ...options + }); + } + /** + * Create a to-do item on an issuable + * + * @example + * ```ts + * const apiEntitiesTodo = + * await client.projects.mergeRequests.todo(0, { id: 'id' }); + * ``` + */ + todo(mergeRequestIid, params, options) { + const { id } = params; + return this._client.post(path3`/projects/${id}/merge_requests/${mergeRequestIid}/todo`, options); + } + /** + * Remove an approval from a merge request + * + * @example + * ```ts + * const apiEntitiesMergeRequestApprovals = + * await client.projects.mergeRequests.unapprove(0, { + * id: 'id', + * }); + * ``` + */ + unapprove(mergeRequestIid, params, options) { + const { id } = params; + return this._client.post(path3`/projects/${id}/merge_requests/${mergeRequestIid}/unapprove`, options); + } + /** + * Unsubscribe from a resource + * + * @example + * ```ts + * const apiEntitiesMergeRequest = + * await client.projects.mergeRequests.unsubscribe( + * 'subscribable_id', + * { id: 'id' }, + * ); + * ``` + */ + unsubscribe(subscribableID, params, options) { + const { id } = params; + return this._client.post(path3`/projects/${id}/merge_requests/${subscribableID}/unsubscribe`, options); + } + /** + * Accept and merge changes submitted with the merge request using this API. + * + * @example + * ```ts + * const apiEntitiesMergeRequest = + * await client.projects.mergeRequests.updateMerge(0, { + * id: 'string', + * }); + * ``` + */ + updateMerge(mergeRequestIid, params, options) { + const { id, ...body } = params; + return this._client.put(path3`/projects/${id}/merge_requests/${mergeRequestIid}/merge`, { + body, + ...options + }); + } + /** + * Automatically rebase the `source_branch` of the merge request against its + * `target_branch`. This feature was added in GitLab 11.6 + * + * @example + * ```ts + * await client.projects.mergeRequests.updateRebase(0, { + * id: 'string', + * }); + * ``` + */ + updateRebase(mergeRequestIid, params, options) { + const { id, ...body } = params; + return this._client.put(path3`/projects/${id}/merge_requests/${mergeRequestIid}/rebase`, { + body, + ...options, + headers: buildHeaders3([{ Accept: "*/*" }, options?.headers]) + }); + } + /** + * Clear all approvals of merge request. This feature was added in GitLab 15.4 + * + * @example + * ```ts + * await client.projects.mergeRequests.updateResetApprovals( + * 0, + * { id: 'id' }, + * ); + * ``` + */ + updateResetApprovals(mergeRequestIid, params, options) { + const { id } = params; + return this._client.put(path3`/projects/${id}/merge_requests/${mergeRequestIid}/reset_approvals`, { + ...options, + headers: buildHeaders3([{ Accept: "*/*" }, options?.headers]) + }); } } - const stepData = outcome[step]; - if (!stepData) { - return null; - } - if (stepData.status === "completed") { - return stepData.completed.conclusion === "success" ? Symbol2.WhiteCheckMark : stepData.completed.conclusion === "skipped" ? Symbol2.Skipped : Symbol2.Exclamation; + BaseMergeRequests3._key = Object.freeze([ + "projects", + "mergeRequests" + ]); + return BaseMergeRequests3; +})(); + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/shims.mjs +function getDefaultFetch3() { + if (typeof fetch !== "undefined") { + return fetch; } - return Symbol2.HourglassFlowingSand; + throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new GitLab({ fetch })` or polyfill the global, `globalThis.fetch = fetch`"); } -function StatusURL(outcome, step) { - if (step === "generate" || !outcome[step]) { - return null; - } - if (outcome[step].status !== "not_started") { - return outcome[step].url; +function makeReadableStream3(...args) { + const ReadableStream = globalThis.ReadableStream; + if (typeof ReadableStream === "undefined") { + throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`"); } + return new ReadableStream(...args); } -function GitHubLink(outcome) { - if (!outcome.commit?.completed?.commit) return null; - const { - repo: { owner, name, branch } - } = outcome.commit.completed.commit; - return Link({ - text: "code", - // This is a staging repo, so it's always GitHub. - href: `https://github.com/${owner}/${name}/tree/${encodeURIComponent(branch)}` +function ReadableStreamFrom3(iterable) { + let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); + return makeReadableStream3({ + start() { + }, + async pull(controller) { + const { done, value } = await iter.next(); + if (done) { + controller.close(); + } else { + controller.enqueue(value); + } + }, + async cancel() { + await iter.return?.(); + } }); } -function CompareLink(base, head) { - if (!base.commit?.completed?.commit || !head.commit?.completed?.commit) { - return null; +async function CancelReadableStream3(stream) { + if (stream === null || typeof stream !== "object") + return; + if (stream[Symbol.asyncIterator]) { + await stream[Symbol.asyncIterator]().return?.(); + return; } - const { repo } = head.commit.completed.commit; - const baseBranch = base.commit.completed.commit.repo.branch; - const headBranch = head.commit.completed.commit.repo.branch; - const compareURL = `https://github.com/${repo.owner}/${repo.name}/compare/${encodeURIComponent(baseBranch)}..${encodeURIComponent(headBranch)}`; - return Link({ text: "diff", href: compareURL }); + const reader = stream.getReader(); + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; } -function MergeConflictLink(outcome) { - if (!outcome.commit?.completed?.merge_conflict_pr) return null; - const { - repo: { owner, name }, - number - } = outcome.commit.completed.merge_conflict_pr; - return Link({ - text: "conflict", - href: `https://github.com/${owner}/${name}/pull/${number}` - }); + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/uploads.mjs +var checkFileSupport3 = () => { + if (typeof File === "undefined") { + const { process: process7 } = globalThis; + const isOldNode = typeof process7?.versions?.node === "string" && parseInt(process7.versions.node.split(".")) < 20; + throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : "")); + } +}; +function makeFile3(fileBits, fileName, options) { + checkFileSupport3(); + return new File(fileBits, fileName ?? "unknown_file", options); } -function DiagnosticsDetails(head, base) { - if (!base.diagnostics || !head.diagnostics) return null; - const newDiagnostics = getNewDiagnostics(head.diagnostics, base.diagnostics); - if (newDiagnostics.length === 0) return null; - const levelCounts = countDiagnosticLevels(newDiagnostics); - const diagnosticCounts = Object.entries(levelCounts).filter(([, count]) => count > 0).map(([level, count]) => `${count} ${level}`); - const diagnosticList = sortDiagnostics(newDiagnostics).slice(0, 10).map((d) => `${DiagnosticIcon[d.level]} ${Bold(d.code)}: ${d.message}`).filter(Boolean); - const tableRows = diagnosticList.map((diagnostic) => ` -${diagnostic} -`).join("\n"); - const tableContent = ` -${tableRows} -
`; - return Details({ - summary: `New diagnostics (${diagnosticCounts.join(", ")})`, - body: tableContent, - indent: false - }); +function getName3(value) { + return (typeof value === "object" && value !== null && ("name" in value && value.name && String(value.name) || "url" in value && value.url && String(value.url) || "filename" in value && value.filename && String(value.filename) || "path" in value && value.path && String(value.path)) || "").split(/[\\/]/).pop() || void 0; } -function InstallationDetails(head, lang) { - let githubGoURL = null; - let installation = null; - if (head.commit?.completed.commit) { - const { repo, sha } = head.commit.completed.commit; - githubGoURL = `github.com/${repo.owner}/${repo.name}@${sha}`; - } - switch (lang) { - case "typescript": - case "node": { - if (head.install_url) { - installation = `npm install ${head.install_url}`; +var isAsyncIterable3 = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function"; +var multipartFormRequestOptions = async (opts, fetch2) => { + return { ...opts, body: await createForm(opts.body, fetch2) }; +}; +var supportsFormDataMap = /* @__PURE__ */ new WeakMap(); +function supportsFormData(fetchObject) { + const fetch2 = typeof fetchObject === "function" ? fetchObject : fetchObject.fetch; + const cached = supportsFormDataMap.get(fetch2); + if (cached) + return cached; + const promise = (async () => { + try { + const FetchResponse = "Response" in fetch2 ? fetch2.Response : (await fetch2("data:,")).constructor; + const data = new FormData(); + if (data.toString() === await new FetchResponse(data).text()) { + return false; } - break; + return true; + } catch { + return true; + } + })(); + supportsFormDataMap.set(fetch2, promise); + return promise; +} +var createForm = async (body, fetch2) => { + if (!await supportsFormData(fetch2)) { + throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class."); + } + const form = new FormData(); + await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value))); + return form; +}; +var isNamedBlob = (value) => value instanceof Blob && "name" in value; +var addFormValue = async (form, key, value) => { + if (value === void 0) + return; + if (value == null) { + throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`); + } + if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { + form.append(key, String(value)); + } else if (value instanceof Response) { + form.append(key, makeFile3([await value.blob()], getName3(value))); + } else if (isAsyncIterable3(value)) { + form.append(key, makeFile3([await new Response(ReadableStreamFrom3(value)).blob()], getName3(value))); + } else if (isNamedBlob(value)) { + form.append(key, value, getName3(value)); + } else if (Array.isArray(value)) { + await Promise.all(value.map((entry) => addFormValue(form, key + "[]", entry))); + } else if (typeof value === "object") { + await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop))); + } else { + throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); + } +}; + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/resources/projects/repository/commits/commits.mjs +var BaseCommits3 = /* @__PURE__ */ (() => { + class BaseCommits4 extends APIResource3 { + /** + * This feature was introduced in GitLab 8.13 + * + * @example + * ```ts + * const apiEntitiesCommitDetail = + * await client.projects.repository.commits.create( + * 'string', + * { file: fs.createReadStream('path/to/file') }, + * ); + * ``` + */ + create(id, body, options) { + return this._client.post(path3`/projects/${id}/repository/commits`, multipartFormRequestOptions({ body, ...options }, this._client)); + } + /** + * Get a specific commit of a project + * + * @example + * ```ts + * const apiEntitiesCommitDetail = + * await client.projects.repository.commits.retrieve('sha', { + * id: 'string', + * }); + * ``` + */ + retrieve(sha, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/repository/commits/${sha}`, { query, ...options }); } - case "python": { - if (head.install_url) { - installation = `pip install ${head.install_url}`; - } - break; + /** + * Get a project repository commits + * + * @example + * ```ts + * const apiEntitiesCommits = + * await client.projects.repository.commits.list('string'); + * ``` + */ + list(id, query = {}, options) { + return this._client.get(path3`/projects/${id}/repository/commits`, { query, ...options }); } - case "go": { - if (githubGoURL) { - installation = `go get ${githubGoURL}`; - } - break; + /** + * Authorize commits upload + * + * @example + * ```ts + * await client.projects.repository.commits.authorize( + * 'string', + * ); + * ``` + */ + authorize(id, options) { + return this._client.post(path3`/projects/${id}/repository/commits/authorize`, { + ...options, + headers: buildHeaders3([{ Accept: "*/*" }, options?.headers]) + }); } - case "java": { - if (head.install_url) { - installation = `Add the following URL as a Maven source: '${head.install_url}'`; - } - break; + /** + * This feature was introduced in GitLab 8.15 + * + * @example + * ```ts + * const apiEntitiesCommit = + * await client.projects.repository.commits.cherryPick( + * 'sha', + * { id: 'string', branch: 'master' }, + * ); + * ``` + */ + cherryPick(sha, params, options) { + const { id, ...body } = params; + return this._client.post(path3`/projects/${id}/repository/commits/${sha}/cherry_pick`, { + body, + ...options + }); } - case "cli": { - if (head.install_url) { - installation = `Download and unzip: '${head.install_url}'. On macOS, run \`xattr -d com.apple.quarantine {executable name}\`.`; - } - break; + /** + * Get the diff for a specific commit of a project + * + * @example + * ```ts + * const apiEntitiesDiffs = + * await client.projects.repository.commits.retrieveDiff( + * 'sha', + * { id: 'string' }, + * ); + * ``` + */ + retrieveDiff(sha, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/repository/commits/${sha}/diff`, { query, ...options }); } - default: { - return null; + /** + * Get Merge Requests associated with a commit + * + * @example + * ```ts + * const apiEntitiesMergeRequestBasic = + * await client.projects.repository.commits.retrieveMergeRequests( + * 'sha', + * { id: 'string' }, + * ); + * ``` + */ + retrieveMergeRequests(sha, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/repository/commits/${sha}/merge_requests`, { + query, + ...options + }); } - } - if (!installation) return null; - return CodeBlock({ content: installation, language: "bash" }); -} -function parseCommitMessages(body) { - if (!body) { - return {}; - } - const targetCommitMessages = {}; - const languageBlocks = body.matchAll( - /\*\*([a-z_]+)\*\*\s*\n```\s*\n([\s\S]*?)\n```/g - ); - for (const match of languageBlocks) { - const language = match[1]; - const message2 = match[2].trim(); - if (message2) { - targetCommitMessages[language] = makeCommitMessageConventional(message2); + /** + * This feature was introduced in GitLab 10.6 + * + * @example + * ```ts + * const response = + * await client.projects.repository.commits.retrieveRefs( + * 'sha', + * { id: 'string' }, + * ); + * ``` + */ + retrieveRefs(sha, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/repository/commits/${sha}/refs`, { query, ...options }); + } + /** + * Get the sequence count of a commit SHA + * + * @example + * ```ts + * const response = + * await client.projects.repository.commits.retrieveSequence( + * 'sha', + * { id: 'string' }, + * ); + * ``` + */ + retrieveSequence(sha, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/repository/commits/${sha}/sequence`, { query, ...options }); + } + /** + * Get a commit's signature + * + * @example + * ```ts + * const response = + * await client.projects.repository.commits.retrieveSignature( + * 'sha', + * { id: 'string' }, + * ); + * ``` + */ + retrieveSignature(sha, params, options) { + const { id } = params; + return this._client.get(path3`/projects/${id}/repository/commits/${sha}/signature`, options); + } + /** + * Get a commit's statuses + * + * @example + * ```ts + * const apiEntitiesCommitStatus = + * await client.projects.repository.commits.retrieveStatuses( + * '18f3e63d05582537db6d183d9d557be09e1f90c8', + * { id: 'string' }, + * ); + * ``` + */ + retrieveStatuses(sha, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/repository/commits/${sha}/statuses`, { query, ...options }); + } + /** + * This feature was introduced in GitLab 11.5 + * + * @example + * ```ts + * const apiEntitiesCommit = + * await client.projects.repository.commits.revert('sha', { + * id: 'string', + * branch: 'master', + * }); + * ``` + */ + revert(sha, params, options) { + const { id, ...body } = params; + return this._client.post(path3`/projects/${id}/repository/commits/${sha}/revert`, { body, ...options }); } } - if (Object.keys(targetCommitMessages).length > 0) { - return { targetCommitMessages }; - } - const message = body?.match(/(? comment.body?.includes(COMMENT_TITLE) - ); - if (!existingComment) { - return null; - } - return { - id: existingComment.id, - ...parseCommitMessages(existingComment.body) - }; -} -async function upsertComment(prNumber, { - body, - skipCreate = false -}) { - logger.debug(`Upserting comment on ${ctx().names.pr} #${prNumber}`); - const comments = await api().listComments(prNumber); - const firstLine = body.trim().split("\n")[0]; - const existingComment = comments.find( - (comment) => comment.body?.includes(firstLine) - ); - if (existingComment) { - logger.debug("Updating existing comment:", existingComment.id); - await api().updateComment(prNumber, { ...existingComment, body }); - } else if (!skipCreate) { - logger.debug("Creating new comment"); - await api().createComment(prNumber, { body }); - } -} -function areCommentsEqual(a, b) { - return a.slice(0, a.indexOf(COMMENT_FOOTER_DIVIDER)) === b.slice(0, b.indexOf(COMMENT_FOOTER_DIVIDER)); + BaseCommits4._key = Object.freeze([ + "projects", + "repository", + "commits" + ]); + return BaseCommits4; +})(); + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/tslib.mjs +function __classPrivateFieldSet3(receiver, state, value, kind, f) { + if (kind === "m") + throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; } -function commentThrottler(prNumber) { - let lastComment = null; - let lastCommentTime = null; - return async ({ body, force = false }) => { - if (force || !lastComment || !lastCommentTime || !areCommentsEqual(body, lastComment) && Date.now() - lastCommentTime.getTime() > 10 * 1e3 || Date.now() - lastCommentTime.getTime() > 30 * 1e3) { - await upsertComment(prNumber, { body }); - lastComment = body; - lastCommentTime = /* @__PURE__ */ new Date(); - } - }; +function __classPrivateFieldGet3(receiver, state, kind, f) { + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); } -// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/context.js -var import_node_process = __toESM(require("node:process"), 1); -var import_node_util = require("node:util"); -var getContext = (raw) => ({ - start: import_node_process.default.hrtime.bigint(), - command: raw.map((part) => getCommandPart((0, import_node_util.stripVTControlCharacters)(part))).join(" "), - state: { stdout: "", stderr: "", output: "" } -}); -var getCommandPart = (part) => /[^\w./-]/.test(part) ? `'${part.replaceAll("'", "'\\''")}'` : part; - -// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/options.js -var import_node_path = __toESM(require("node:path"), 1); -var import_node_url = require("node:url"); -var import_node_process2 = __toESM(require("node:process"), 1); -var getOptions = ({ - stdin, - stdout, - stderr, - stdio = [stdin, stdout, stderr], - env: envOption, - preferLocal, - cwd: cwdOption = ".", - ...options -}) => { - const cwd = cwdOption instanceof URL ? (0, import_node_url.fileURLToPath)(cwdOption) : import_node_path.default.resolve(cwdOption); - const env = envOption ? { ...import_node_process2.default.env, ...envOption } : void 0; - const input = stdio[0]?.string; - return { - ...options, - input, - stdio: input === void 0 ? stdio : ["pipe", ...stdio.slice(1)], - env: preferLocal ? addLocalPath(env ?? import_node_process2.default.env, cwd) : env, - cwd - }; -}; -var addLocalPath = ({ Path: Path3 = "", PATH = Path3, ...env }, cwd) => { - const pathParts = PATH.split(import_node_path.default.delimiter); - const localPaths = getLocalPaths([], import_node_path.default.resolve(cwd)).map((localPath) => import_node_path.default.join(localPath, "node_modules/.bin")).filter((localPath) => !pathParts.includes(localPath)); - return { ...env, PATH: [...localPaths, PATH].filter(Boolean).join(import_node_path.default.delimiter) }; +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/utils/uuid.mjs +var uuid43 = function() { + const { crypto: crypto2 } = globalThis; + if (crypto2?.randomUUID) { + uuid43 = crypto2.randomUUID.bind(crypto2); + return crypto2.randomUUID(); + } + const u8 = new Uint8Array(1); + const randomByte = crypto2 ? () => crypto2.getRandomValues(u8)[0] : () => Math.random() * 255 & 255; + return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16)); }; -var getLocalPaths = (localPaths, localPath) => localPaths.at(-1) === localPath ? localPaths : getLocalPaths([...localPaths, localPath], import_node_path.default.resolve(localPath, "..")); -// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/spawn.js -var import_node_child_process = require("node:child_process"); -var import_node_events2 = require("node:events"); -var import_node_process5 = __toESM(require("node:process"), 1); +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/utils/sleep.mjs +var sleep3 = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); -// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/windows.js -var import_promises = __toESM(require("node:fs/promises"), 1); -var import_node_path2 = __toESM(require("node:path"), 1); -var import_node_process3 = __toESM(require("node:process"), 1); -var applyForceShell = async (file, commandArguments, options) => await shouldForceShell(file, options) ? [escapeFile(file), commandArguments.map((argument) => escapeArgument(argument)), { ...options, shell: true }] : [file, commandArguments, options]; -var shouldForceShell = async (file, { shell, cwd, env = import_node_process3.default.env }) => import_node_process3.default.platform === "win32" && !shell && !await isExe(file, cwd, env); -var isExe = (file, cwd, { Path: Path3 = "", PATH = Path3 }) => ( - // If the *.exe or *.com file extension was not omitted. - // Windows common file systems are case-insensitive. - exeExtensions.some((extension) => file.toLowerCase().endsWith(extension)) || mIsExe(file, cwd, PATH) -); -var EXE_MEMO = {}; -var memoize = (function_) => (...arguments_) => ( - // Use returned assignment to keep code small - EXE_MEMO[arguments_.join("\0")] ??= function_(...arguments_) -); -var access = memoize(import_promises.default.access); -var mIsExe = memoize(async (file, cwd, PATH) => { - const parts = PATH.split(import_node_path2.default.delimiter).filter(Boolean).map((part) => part.replace(/^"(.*)"$/, "$1")); - try { - await Promise.any( - [cwd, ...parts].flatMap( - (part) => exeExtensions.map((extension) => access(`${import_node_path2.default.resolve(part, file)}${extension}`)) - ) - ); - } catch { - return false; - } - return true; -}); -var exeExtensions = [".exe", ".com"]; -var escapeArgument = (argument) => escapeFile(escapeFile(`"${argument.replaceAll(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, "$1$1")}"`)); -var escapeFile = (file) => file.replaceAll(/([()\][%!^"`<>&|;, *?])/g, "^$1"); +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/version.mjs +var VERSION3 = "0.3.0"; -// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/result.js -var import_node_events = require("node:events"); -var import_node_process4 = __toESM(require("node:process"), 1); -var getResult = async (nodeChildProcess, { input }, context) => { - const instance = await nodeChildProcess; - if (input !== void 0) { - instance.stdin.end(input); - } - const onClose = (0, import_node_events.once)(instance, "close"); - try { - await Promise.race([ - onClose, - ...instance.stdio.filter(Boolean).map((stream) => onStreamError(stream)) - ]); - checkFailure(context, getErrorOutput(instance)); - return getOutputs(context); - } catch (error) { - await Promise.allSettled([onClose]); - throw getResultError(error, instance, context); - } -}; -var onStreamError = async (stream) => { - for await (const [error] of (0, import_node_events.on)(stream, "error")) { - if (!["ERR_STREAM_PREMATURE_CLOSE", "EPIPE"].includes(error?.code)) { - throw error; - } - } -}; -var checkFailure = ({ command }, { exitCode, signalName }) => { - if (signalName !== void 0) { - throw new SubprocessError(`Command was terminated with ${signalName}: ${command}`); +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/detect-platform.mjs +function getDetectedPlatform3() { + if (typeof Deno !== "undefined" && Deno.build != null) { + return "deno"; } - if (exitCode !== void 0) { - throw new SubprocessError(`Command failed with exit code ${exitCode}: ${command}`); + if (typeof EdgeRuntime !== "undefined") { + return "edge"; } -}; -var getResultError = (error, instance, context) => Object.assign( - getErrorInstance(error, context), - getErrorOutput(instance), - getOutputs(context) -); -var getErrorInstance = (error, { command }) => error instanceof SubprocessError ? error : new SubprocessError(`Command failed: ${command}`, { cause: error }); -var SubprocessError = class extends Error { - name = "SubprocessError"; -}; -var getErrorOutput = ({ exitCode, signalCode }) => ({ - // `exitCode` can be a negative number (`errno`) when the `error` event is emitted on the `instance` - ...exitCode < 1 ? {} : { exitCode }, - ...signalCode === null ? {} : { signalName: signalCode } -}); -var getOutputs = ({ state: { stdout, stderr, output }, command, start }) => ({ - stdout: getOutput(stdout), - stderr: getOutput(stderr), - output: getOutput(output), - command, - durationMs: Number(import_node_process4.default.hrtime.bigint() - start) / 1e6 -}); -var getOutput = (output) => output.at(-1) === "\n" ? output.slice(0, output.at(-2) === "\r" ? -2 : -1) : output; - -// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/spawn.js -var spawnSubprocess = async (file, commandArguments, options, context) => { - try { - if (["node", "node.exe"].includes(file.toLowerCase())) { - file = import_node_process5.default.execPath; - commandArguments = [...import_node_process5.default.execArgv.filter((flag) => !flag.startsWith("--inspect")), ...commandArguments]; - } - [file, commandArguments, options] = await applyForceShell(file, commandArguments, options); - [file, commandArguments, options] = concatenateShell(file, commandArguments, options); - const instance = (0, import_node_child_process.spawn)(file, commandArguments, options); - bufferOutput(instance.stdout, context, "stdout"); - bufferOutput(instance.stderr, context, "stderr"); - instance.once("error", () => { - }); - await (0, import_node_events2.once)(instance, "spawn"); - return instance; - } catch (error) { - throw getResultError(error, {}, context); + if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") { + return "node"; } -}; -var concatenateShell = (file, commandArguments, options) => options.shell && commandArguments.length > 0 ? [[file, ...commandArguments].join(" "), [], options] : [file, commandArguments, options]; -var bufferOutput = (stream, { state }, streamName) => { - if (stream) { - stream.setEncoding("utf8"); - if (!state.isIterating) { - state.isIterating = false; - stream.on("data", (chunk) => { - state[streamName] += chunk; - state.output += chunk; - }); - } + return "unknown"; +} +var getPlatformProperties3 = () => { + const detectedPlatform = getDetectedPlatform3(); + if (detectedPlatform === "deno") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION3, + "X-Stainless-OS": normalizePlatform3(Deno.build.os), + "X-Stainless-Arch": normalizeArch3(Deno.build.arch), + "X-Stainless-Runtime": "deno", + "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown" + }; } -}; - -// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/pipe.js -var import_promises2 = require("node:stream/promises"); -var handlePipe = async (subprocesses) => { - const [[from, to]] = await Promise.all([Promise.allSettled(subprocesses), pipeStreams(subprocesses)]); - if (to.reason) { - to.reason.pipedFrom = from.reason ?? from.value; - throw to.reason; + if (typeof EdgeRuntime !== "undefined") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION3, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": `other:${EdgeRuntime}`, + "X-Stainless-Runtime": "edge", + "X-Stainless-Runtime-Version": globalThis.process.version + }; } - if (from.reason) { - throw from.reason; + if (detectedPlatform === "node") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION3, + "X-Stainless-OS": normalizePlatform3(globalThis.process.platform ?? "unknown"), + "X-Stainless-Arch": normalizeArch3(globalThis.process.arch ?? "unknown"), + "X-Stainless-Runtime": "node", + "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown" + }; } - return { ...to.value, pipedFrom: from.value }; -}; -var pipeStreams = async (subprocesses) => { - try { - const [{ stdout }, { stdin }] = await Promise.all(subprocesses.map(({ nodeChildProcess }) => nodeChildProcess)); - if (stdin === null) { - throw new Error('The "stdin" option must be set on the first "spawn()" call in the pipeline.'); - } - if (stdout === null) { - throw new Error('The "stdout" option must be set on the last "spawn()" call in the pipeline.'); - } - (0, import_promises2.pipeline)(stdout, stdin).catch(() => { - }); - } catch (error) { - await Promise.allSettled(subprocesses.map(({ nodeChildProcess }) => closeStdin(nodeChildProcess))); - throw error; + const browserInfo = getBrowserInfo3(); + if (browserInfo) { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION3, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": "unknown", + "X-Stainless-Runtime": `browser:${browserInfo.browser}`, + "X-Stainless-Runtime-Version": browserInfo.version + }; } + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION3, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": "unknown", + "X-Stainless-Runtime": "unknown", + "X-Stainless-Runtime-Version": "unknown" + }; }; -var closeStdin = async (nodeChildProcess) => { - const { stdin } = await nodeChildProcess; - stdin.end(); -}; - -// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/iterable.js -var readline = __toESM(require("node:readline/promises"), 1); -var lineIterator = async function* (subprocess, { state }, streamName) { - if (state.isIterating === false) { - throw new Error(`The subprocess must be iterated right away, for example: - for await (const line of spawn(...)) { ... }`); +function getBrowserInfo3() { + if (typeof navigator === "undefined" || !navigator) { + return null; } - state.isIterating = true; - try { - const { [streamName]: stream } = await subprocess.nodeChildProcess; - if (!stream) { - return; + const browserPatterns = [ + { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ } + ]; + for (const { key, pattern } of browserPatterns) { + const match = pattern.exec(navigator.userAgent); + if (match) { + const major = match[1] || 0; + const minor = match[2] || 0; + const patch = match[3] || 0; + return { browser: key, version: `${major}.${minor}.${patch}` }; } - handleErrors(subprocess); - yield* readline.createInterface({ input: stream }); - } finally { - await subprocess; } + return null; +} +var normalizeArch3 = (arch) => { + if (arch === "x32") + return "x32"; + if (arch === "x86_64" || arch === "x64") + return "x64"; + if (arch === "arm") + return "arm"; + if (arch === "aarch64" || arch === "arm64") + return "arm64"; + if (arch) + return `other:${arch}`; + return "unknown"; }; -var handleErrors = async (subprocess) => { - try { - await subprocess; - } catch { - } +var normalizePlatform3 = (platform) => { + platform = platform.toLowerCase(); + if (platform.includes("ios")) + return "iOS"; + if (platform === "android") + return "Android"; + if (platform === "darwin") + return "MacOS"; + if (platform === "win32") + return "Windows"; + if (platform === "freebsd") + return "FreeBSD"; + if (platform === "openbsd") + return "OpenBSD"; + if (platform === "linux") + return "Linux"; + if (platform) + return `Other:${platform}`; + return "Unknown"; }; -var combineAsyncIterators = async function* (...iterators) { - try { - let promises = []; - while (iterators.length > 0) { - promises = iterators.map((iterator2, index2) => promises[index2] ?? getNext(iterator2)); - const [{ value, done }, index] = await Promise.race(promises.map((promise, index2) => Promise.all([promise, index2]))); - const [iterator] = iterators.splice(index, 1); - promises.splice(index, 1); - if (!done) { - iterators.push(iterator); - yield value; - } - } - } finally { - await Promise.all(iterators.map((iterator) => iterator.return())); - } +var _platformHeaders3; +var getPlatformHeaders3 = () => { + return _platformHeaders3 ?? (_platformHeaders3 = getPlatformProperties3()); }; -var getNext = async (iterator) => { - try { - return await iterator.next(); - } catch (error) { - await iterator.throw(error); - } + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/request-options.mjs +var FallbackEncoder3 = ({ headers, body }) => { + return { + bodyHeaders: { + "content-type": "application/json" + }, + body: JSON.stringify(body) + }; }; -// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/index.js -function spawn2(file, second, third, previous) { - const [commandArguments = [], options = {}] = Array.isArray(second) ? [second, third] : [[], second]; - const context = getContext([file, ...commandArguments]); - const spawnOptions = getOptions(options); - const nodeChildProcess = spawnSubprocess(file, commandArguments, spawnOptions, context); - let subprocess = getResult(nodeChildProcess, spawnOptions, context); - Object.assign(subprocess, { nodeChildProcess }); - subprocess = previous ? handlePipe([previous, subprocess]) : subprocess; - const stdout = lineIterator(subprocess, context, "stdout"); - const stderr = lineIterator(subprocess, context, "stderr"); - return Object.assign(subprocess, { - nodeChildProcess, - stdout, - stderr, - [Symbol.asyncIterator]: () => combineAsyncIterators(stdout, stderr), - pipe: (file2, second2, third2) => spawn2(file2, second2, third2, subprocess) - }); -} +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/qs/formats.mjs +var default_format3 = "RFC3986"; +var default_formatter3 = (v) => String(v); +var formatters3 = { + RFC1738: (v) => String(v).replace(/%20/g, "+"), + RFC3986: default_formatter3 +}; +var RFC17383 = "RFC1738"; -// src/config.ts -var fs4 = __toESM(require("node:fs")); -var import_node_os = require("node:os"); -var path5 = __toESM(require("node:path")); -function getSavedFilePath(file, sha, extension) { - return path5.join( - (0, import_node_os.tmpdir)(), - "stainless-generated-config", - `${file}-${sha}${extension}` - ); -} -async function saveConfig({ - oasPath, - configPath -}) { - let hasOAS = false; - let hasConfig = false; - const savedSha = (await spawn2("git", ["rev-parse", "HEAD"])).stdout.trim(); - if (!savedSha) { - throw new Error("Unable to determine current SHA; is there a git repo?"); +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/qs/utils.mjs +var has3 = (obj, key) => (has3 = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has3(obj, key)); +var hex_table3 = /* @__PURE__ */ (() => { + const array = []; + for (let i = 0; i < 256; ++i) { + array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase()); } - logger.info("Saving generated config for", savedSha); - if (oasPath && fs4.existsSync(oasPath)) { - hasOAS = true; - const savedFilePath = getSavedFilePath( - "oas", - savedSha, - path5.extname(oasPath) - ); - fs4.mkdirSync(path5.dirname(savedFilePath), { recursive: true }); - fs4.copyFileSync(oasPath, savedFilePath); - fs4.rmSync(oasPath); - logger.info(`Saved OAS file to ${savedFilePath}`); + return array; +})(); +var limit3 = 1024; +var encode3 = (str, _defaultEncoder, charset, _kind, format) => { + if (str.length === 0) { + return str; } - if (configPath && fs4.existsSync(configPath)) { - hasConfig = true; - const savedFilePath = getSavedFilePath( - "config", - savedSha, - path5.extname(configPath) - ); - fs4.mkdirSync(path5.dirname(savedFilePath), { recursive: true }); - fs4.copyFileSync(configPath, savedFilePath); - fs4.rmSync(configPath); - logger.info(`Saved config file to ${savedFilePath}`); + let string = str; + if (typeof str === "symbol") { + string = Symbol.prototype.toString.call(str); + } else if (typeof str !== "string") { + string = String(str); } - return { hasOAS, hasConfig, savedSha }; -} -async function readConfig({ - oasPath, - configPath, - sha, - required = false -}) { - sha ??= (await spawn2("git", ["rev-parse", "HEAD"])).stdout; - if (!sha) { - throw new Error("Unable to determine current SHA; is there a git repo?"); + if (charset === "iso-8859-1") { + return escape(string).replace(/%u[0-9a-f]{4}/gi, function($0) { + return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; + }); } - logger.info("Reading config at SHA", sha); - const results = {}; - const addToResults = async (file, filePath, via) => { - if (results[file]) { - return; - } - if (!filePath || !fs4.existsSync(filePath)) { - logger.debug(`Skipping missing ${file} at ${filePath}`); - return; + let out = ""; + for (let j = 0; j < string.length; j += limit3) { + const segment = string.length >= limit3 ? string.slice(j, j + limit3) : string; + const arr = []; + for (let i = 0; i < segment.length; ++i) { + let c = segment.charCodeAt(i); + if (c === 45 || // - + c === 46 || // . + c === 95 || // _ + c === 126 || // ~ + c >= 48 && c <= 57 || // 0-9 + c >= 65 && c <= 90 || // a-z + c >= 97 && c <= 122 || // A-Z + format === RFC17383 && (c === 40 || c === 41)) { + arr[arr.length] = segment.charAt(i); + continue; + } + if (c < 128) { + arr[arr.length] = hex_table3[c]; + continue; + } + if (c < 2048) { + arr[arr.length] = hex_table3[192 | c >> 6] + hex_table3[128 | c & 63]; + continue; + } + if (c < 55296 || c >= 57344) { + arr[arr.length] = hex_table3[224 | c >> 12] + hex_table3[128 | c >> 6 & 63] + hex_table3[128 | c & 63]; + continue; + } + i += 1; + c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023); + arr[arr.length] = hex_table3[240 | c >> 18] + hex_table3[128 | c >> 12 & 63] + hex_table3[128 | c >> 6 & 63] + hex_table3[128 | c & 63]; } - results[file] = fs4.readFileSync(filePath, "utf-8"); - results[`${file}Hash`] = (await spawn2("md5sum", [filePath])).stdout.split( - " " - )[0]; - logger.info(`Using ${file} via ${via}`, { hash: results[`${file}Hash`] }); - }; - try { - await spawn2("git", ["fetch", "--depth=1", "origin", sha]).catch(() => null); - await spawn2("git", ["checkout", sha, "--", "."]); - } catch { - logger.debug("Could not checkout", sha); - } - await addToResults("oas", oasPath, `git ${sha}`); - await addToResults("config", configPath, `git ${sha}`); - try { - await addToResults( - "oas", - getSavedFilePath("oas", sha, path5.extname(oasPath ?? "")), - `saved ${sha}` - ); - await addToResults( - "config", - getSavedFilePath("config", sha, path5.extname(configPath ?? "")), - `saved ${sha}` - ); - } catch (e) { - logger.info(`Could not get config from saved file path: ${e}`); - logger.debug("Could not get config from saved file path"); + out += arr.join(""); } - if (required) { - if (oasPath && !results.oas) { - throw new Error(`Missing OpenAPI spec at ${oasPath} for ${sha}`); - } - if (configPath && !results.config) { - throw new Error(`Missing config at ${configPath} for ${sha}`); - } + return out; +}; +function is_buffer3(obj) { + if (!obj || typeof obj !== "object") { + return false; } - return results; + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); } -async function isConfigChanged({ - before, - after -}) { - let changed = false; - if (before.oasHash !== after.oasHash) { - logger.debug("OAS file changed"); - changed = true; - } - if (before.configHash !== after.configHash) { - logger.debug("Config file changed"); - changed = true; +function maybe_map3(val, fn) { + if (isArray3(val)) { + const mapped = []; + for (let i = 0; i < val.length; i += 1) { + mapped.push(fn(val[i])); + } + return mapped; } - return changed; + return fn(val); } -// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/diff/base.js -var Diff = class { - diff(oldStr, newStr, options = {}) { - let callback; - if (typeof options === "function") { - callback = options; - options = {}; - } else if ("callback" in options) { - callback = options.callback; - } - const oldString = this.castInput(oldStr, options); - const newString = this.castInput(newStr, options); - const oldTokens = this.removeEmpty(this.tokenize(oldString, options)); - const newTokens = this.removeEmpty(this.tokenize(newString, options)); - return this.diffWithOptionsObj(oldTokens, newTokens, options, callback); +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/qs/stringify.mjs +var array_prefix_generators3 = { + brackets(prefix) { + return String(prefix) + "[]"; + }, + comma: "comma", + indices(prefix, key) { + return String(prefix) + "[" + key + "]"; + }, + repeat(prefix) { + return String(prefix); } - diffWithOptionsObj(oldTokens, newTokens, options, callback) { - var _a2; - const done = (value) => { - value = this.postProcess(value, options); - if (callback) { - setTimeout(function() { - callback(value); - }, 0); - return void 0; +}; +var push_to_array3 = function(arr, value_or_array) { + Array.prototype.push.apply(arr, isArray3(value_or_array) ? value_or_array : [value_or_array]); +}; +var toISOString3; +var defaults3 = { + addQueryPrefix: false, + allowDots: false, + allowEmptyArrays: false, + arrayFormat: "indices", + charset: "utf-8", + charsetSentinel: false, + delimiter: "&", + encode: true, + encodeDotInKeys: false, + encoder: encode3, + encodeValuesOnly: false, + format: default_format3, + formatter: default_formatter3, + /** @deprecated */ + indices: false, + serializeDate(date) { + return (toISOString3 ?? (toISOString3 = Function.prototype.call.bind(Date.prototype.toISOString)))(date); + }, + skipNulls: false, + strictNullHandling: false +}; +function is_non_nullish_primitive3(v) { + return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint"; +} +var sentinel3 = {}; +function inner_stringify3(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { + let obj = object; + let tmp_sc = sideChannel; + let step = 0; + let find_flag = false; + while ((tmp_sc = tmp_sc.get(sentinel3)) !== void 0 && !find_flag) { + const pos = tmp_sc.get(object); + step += 1; + if (typeof pos !== "undefined") { + if (pos === step) { + throw new RangeError("Cyclic object value"); } else { - return value; - } - }; - const newLen = newTokens.length, oldLen = oldTokens.length; - let editLength = 1; - let maxEditLength = newLen + oldLen; - if (options.maxEditLength != null) { - maxEditLength = Math.min(maxEditLength, options.maxEditLength); - } - const maxExecutionTime = (_a2 = options.timeout) !== null && _a2 !== void 0 ? _a2 : Infinity; - const abortAfterTimestamp = Date.now() + maxExecutionTime; - const bestPath = [{ oldPos: -1, lastComponent: void 0 }]; - let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options); - if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) { - return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens)); - } - let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity; - const execEditLength = () => { - for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) { - let basePath; - const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1]; - if (removePath) { - bestPath[diagonalPath - 1] = void 0; - } - let canAdd = false; - if (addPath) { - const addPathNewPos = addPath.oldPos - diagonalPath; - canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen; - } - const canRemove = removePath && removePath.oldPos + 1 < oldLen; - if (!canAdd && !canRemove) { - bestPath[diagonalPath] = void 0; - continue; - } - if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) { - basePath = this.addToPath(addPath, true, false, 0, options); - } else { - basePath = this.addToPath(removePath, false, true, 1, options); - } - newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options); - if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) { - return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true; - } else { - bestPath[diagonalPath] = basePath; - if (basePath.oldPos + 1 >= oldLen) { - maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1); - } - if (newPos + 1 >= newLen) { - minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1); - } - } - } - editLength++; - }; - if (callback) { - (function exec() { - setTimeout(function() { - if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) { - return callback(void 0); - } - if (!execEditLength()) { - exec(); - } - }, 0); - })(); - } else { - while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) { - const ret = execEditLength(); - if (ret) { - return ret; - } + find_flag = true; } } - } - addToPath(path7, added, removed, oldPosInc, options) { - const last = path7.lastComponent; - if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) { - return { - oldPos: path7.oldPos + oldPosInc, - lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent } - }; - } else { - return { - oldPos: path7.oldPos + oldPosInc, - lastComponent: { count: 1, added, removed, previousComponent: last } - }; + if (typeof tmp_sc.get(sentinel3) === "undefined") { + step = 0; } } - extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) { - const newLen = newTokens.length, oldLen = oldTokens.length; - let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0; - while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) { - newPos++; - oldPos++; - commonCount++; - if (options.oneChangePerToken) { - basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false }; + if (typeof filter === "function") { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate?.(obj); + } else if (generateArrayPrefix === "comma" && isArray3(obj)) { + obj = maybe_map3(obj, function(value) { + if (value instanceof Date) { + return serializeDate?.(value); } + return value; + }); + } + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? ( + // @ts-expect-error + encoder(prefix, defaults3.encoder, charset, "key", format) + ) : prefix; } - if (commonCount && !options.oneChangePerToken) { - basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false }; - } - basePath.oldPos = oldPos; - return newPos; + obj = ""; } - equals(left, right, options) { - if (options.comparator) { - return options.comparator(left, right); - } else { - return left === right || !!options.ignoreCase && left.toLowerCase() === right.toLowerCase(); + if (is_non_nullish_primitive3(obj) || is_buffer3(obj)) { + if (encoder) { + const key_value = encodeValuesOnly ? prefix : encoder(prefix, defaults3.encoder, charset, "key", format); + return [ + formatter?.(key_value) + "=" + // @ts-expect-error + formatter?.(encoder(obj, defaults3.encoder, charset, "value", format)) + ]; } + return [formatter?.(prefix) + "=" + formatter?.(String(obj))]; } - removeEmpty(array) { - const ret = []; - for (let i = 0; i < array.length; i++) { - if (array[i]) { - ret.push(array[i]); - } + const values = []; + if (typeof obj === "undefined") { + return values; + } + let obj_keys; + if (generateArrayPrefix === "comma" && isArray3(obj)) { + if (encodeValuesOnly && encoder) { + obj = maybe_map3(obj, encoder); } - return ret; + obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; + } else if (isArray3(filter)) { + obj_keys = filter; + } else { + const keys = Object.keys(obj); + obj_keys = sort ? keys.sort(sort) : keys; } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - castInput(value, options) { - return value; + const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix); + const adjusted_prefix = commaRoundTrip && isArray3(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix; + if (allowEmptyArrays && isArray3(obj) && obj.length === 0) { + return adjusted_prefix + "[]"; } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - tokenize(value, options) { - return Array.from(value); + for (let j = 0; j < obj_keys.length; ++j) { + const key = obj_keys[j]; + const value = ( + // @ts-ignore + typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key] + ); + if (skipNulls && value === null) { + continue; + } + const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key; + const key_prefix = isArray3(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]"); + sideChannel.set(object, step); + const valueSideChannel = /* @__PURE__ */ new WeakMap(); + valueSideChannel.set(sentinel3, sideChannel); + push_to_array3(values, inner_stringify3( + value, + key_prefix, + generateArrayPrefix, + commaRoundTrip, + allowEmptyArrays, + strictNullHandling, + skipNulls, + encodeDotInKeys, + // @ts-ignore + generateArrayPrefix === "comma" && encodeValuesOnly && isArray3(obj) ? null : encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + valueSideChannel + )); } - join(chars) { - return chars.join(""); + return values; +} +function normalize_stringify_options3(opts = defaults3) { + if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") { + throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); } - postProcess(changeObjects, options) { - return changeObjects; + if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") { + throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided"); } - get useLongestToken() { - return false; + if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") { + throw new TypeError("Encoder has to be a function."); } - buildValues(lastComponent, newTokens, oldTokens) { - const components = []; - let nextComponent; - while (lastComponent) { - components.push(lastComponent); - nextComponent = lastComponent.previousComponent; - delete lastComponent.previousComponent; - lastComponent = nextComponent; - } - components.reverse(); - const componentLen = components.length; - let componentPos = 0, newPos = 0, oldPos = 0; - for (; componentPos < componentLen; componentPos++) { - const component = components[componentPos]; - if (!component.removed) { - if (!component.added && this.useLongestToken) { - let value = newTokens.slice(newPos, newPos + component.count); - value = value.map(function(value2, i) { - const oldValue = oldTokens[oldPos + i]; - return oldValue.length > value2.length ? oldValue : value2; - }); - component.value = this.join(value); - } else { - component.value = this.join(newTokens.slice(newPos, newPos + component.count)); - } - newPos += component.count; - if (!component.added) { - oldPos += component.count; - } - } else { - component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count)); - oldPos += component.count; - } + const charset = opts.charset || defaults3.charset; + if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { + throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); + } + let format = default_format3; + if (typeof opts.format !== "undefined") { + if (!has3(formatters3, opts.format)) { + throw new TypeError("Unknown format option provided."); } - return components; + format = opts.format; } -}; - -// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/util/string.js -function hasOnlyWinLineEndings(string) { - return string.includes("\r\n") && !string.startsWith("\n") && !string.match(/[^\r]\n/); -} -function hasOnlyUnixLineEndings(string) { - return !string.includes("\r\n") && string.includes("\n"); -} - -// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/diff/line.js -var LineDiff = class extends Diff { - constructor() { - super(...arguments); - this.tokenize = tokenize; + const formatter = formatters3[format]; + let filter = defaults3.filter; + if (typeof opts.filter === "function" || isArray3(opts.filter)) { + filter = opts.filter; } - equals(left, right, options) { - if (options.ignoreWhitespace) { - if (!options.newlineIsToken || !left.includes("\n")) { - left = left.trim(); - } - if (!options.newlineIsToken || !right.includes("\n")) { - right = right.trim(); - } - } else if (options.ignoreNewlineAtEof && !options.newlineIsToken) { - if (left.endsWith("\n")) { - left = left.slice(0, -1); - } - if (right.endsWith("\n")) { - right = right.slice(0, -1); - } - } - return super.equals(left, right, options); + let arrayFormat; + if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators3) { + arrayFormat = opts.arrayFormat; + } else if ("indices" in opts) { + arrayFormat = opts.indices ? "indices" : "repeat"; + } else { + arrayFormat = defaults3.arrayFormat; } -}; -var lineDiff = new LineDiff(); -function diffLines(oldStr, newStr, options) { - return lineDiff.diff(oldStr, newStr, options); + if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") { + throw new TypeError("`commaRoundTrip` must be a boolean, or absent"); + } + const allowDots = typeof opts.allowDots === "undefined" ? !!opts.encodeDotInKeys === true ? true : defaults3.allowDots : !!opts.allowDots; + return { + addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults3.addQueryPrefix, + // @ts-ignore + allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults3.allowEmptyArrays, + arrayFormat, + charset, + charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults3.charsetSentinel, + commaRoundTrip: !!opts.commaRoundTrip, + delimiter: typeof opts.delimiter === "undefined" ? defaults3.delimiter : opts.delimiter, + encode: typeof opts.encode === "boolean" ? opts.encode : defaults3.encode, + encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults3.encodeDotInKeys, + encoder: typeof opts.encoder === "function" ? opts.encoder : defaults3.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults3.encodeValuesOnly, + filter, + format, + formatter, + serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults3.serializeDate, + skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults3.skipNulls, + // @ts-ignore + sort: typeof opts.sort === "function" ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults3.strictNullHandling + }; } -function tokenize(value, options) { - if (options.stripTrailingCr) { - value = value.replace(/\r\n/g, "\n"); +function stringify3(object, opts = {}) { + let obj = object; + const options = normalize_stringify_options3(opts); + let obj_keys; + let filter; + if (typeof options.filter === "function") { + filter = options.filter; + obj = filter("", obj); + } else if (isArray3(options.filter)) { + filter = options.filter; + obj_keys = filter; } - const retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/); - if (!linesAndNewlines[linesAndNewlines.length - 1]) { - linesAndNewlines.pop(); + const keys = []; + if (typeof obj !== "object" || obj === null) { + return ""; + } + const generateArrayPrefix = array_prefix_generators3[options.arrayFormat]; + const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip; + if (!obj_keys) { + obj_keys = Object.keys(obj); + } + if (options.sort) { + obj_keys.sort(options.sort); + } + const sideChannel = /* @__PURE__ */ new WeakMap(); + for (let i = 0; i < obj_keys.length; ++i) { + const key = obj_keys[i]; + if (options.skipNulls && obj[key] === null) { + continue; + } + push_to_array3(keys, inner_stringify3( + obj[key], + key, + // @ts-expect-error + generateArrayPrefix, + commaRoundTrip, + options.allowEmptyArrays, + options.strictNullHandling, + options.skipNulls, + options.encodeDotInKeys, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.format, + options.formatter, + options.encodeValuesOnly, + options.charset, + sideChannel + )); } - for (let i = 0; i < linesAndNewlines.length; i++) { - const line = linesAndNewlines[i]; - if (i % 2 && !options.newlineIsToken) { - retLines[retLines.length - 1] += line; + const joined = keys.join(options.delimiter); + let prefix = options.addQueryPrefix === true ? "?" : ""; + if (options.charsetSentinel) { + if (options.charset === "iso-8859-1") { + prefix += "utf8=%26%2310003%3B&"; } else { - retLines.push(line); + prefix += "utf8=%E2%9C%93&"; } } - return retLines; + return joined.length > 0 ? prefix + joined : ""; } -// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/line-endings.js -function unixToWin(patch) { - if (Array.isArray(patch)) { - return patch.map((p) => unixToWin(p)); +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/utils/log.mjs +var levelNumbers3 = { + off: 0, + error: 200, + warn: 300, + info: 400, + debug: 500 +}; +var parseLogLevel3 = (maybeLevel, sourceName, client) => { + if (!maybeLevel) { + return void 0; } - return Object.assign(Object.assign({}, patch), { hunks: patch.hunks.map((hunk) => Object.assign(Object.assign({}, hunk), { lines: hunk.lines.map((line, i) => { - var _a2; - return line.startsWith("\\") || line.endsWith("\r") || ((_a2 = hunk.lines[i + 1]) === null || _a2 === void 0 ? void 0 : _a2.startsWith("\\")) ? line : line + "\r"; - }) })) }); -} -function winToUnix(patch) { - if (Array.isArray(patch)) { - return patch.map((p) => winToUnix(p)); + if (hasOwn3(levelNumbers3, maybeLevel)) { + return maybeLevel; } - return Object.assign(Object.assign({}, patch), { hunks: patch.hunks.map((hunk) => Object.assign(Object.assign({}, hunk), { lines: hunk.lines.map((line) => line.endsWith("\r") ? line.substring(0, line.length - 1) : line) })) }); + loggerFor3(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers3))}`); + return void 0; +}; +function noop3() { } -function isUnix(patch) { - if (!Array.isArray(patch)) { - patch = [patch]; +function makeLogFn3(fnLevel, logger2, logLevel) { + if (!logger2 || levelNumbers3[fnLevel] > levelNumbers3[logLevel]) { + return noop3; + } else { + return logger2[fnLevel].bind(logger2); } - return !patch.some((index) => index.hunks.some((hunk) => hunk.lines.some((line) => !line.startsWith("\\") && line.endsWith("\r")))); } -function isWin(patch) { - if (!Array.isArray(patch)) { - patch = [patch]; +var noopLogger3 = { + error: noop3, + warn: noop3, + info: noop3, + debug: noop3 +}; +var cachedLoggers3 = /* @__PURE__ */ new WeakMap(); +function loggerFor3(client) { + const logger2 = client.logger; + const logLevel = client.logLevel ?? "off"; + if (!logger2) { + return noopLogger3; } - return patch.some((index) => index.hunks.some((hunk) => hunk.lines.some((line) => line.endsWith("\r")))) && patch.every((index) => index.hunks.every((hunk) => hunk.lines.every((line, i) => { - var _a2; - return line.startsWith("\\") || line.endsWith("\r") || ((_a2 = hunk.lines[i + 1]) === null || _a2 === void 0 ? void 0 : _a2.startsWith("\\")); - }))); + const cachedLogger = cachedLoggers3.get(logger2); + if (cachedLogger && cachedLogger[0] === logLevel) { + return cachedLogger[1]; + } + const levelLogger = { + error: makeLogFn3("error", logger2, logLevel), + warn: makeLogFn3("warn", logger2, logLevel), + info: makeLogFn3("info", logger2, logLevel), + debug: makeLogFn3("debug", logger2, logLevel) + }; + cachedLoggers3.set(logger2, [logLevel, levelLogger]); + return levelLogger; } +var formatRequestDetails3 = (details) => { + if (details.options) { + details.options = { ...details.options }; + delete details.options["headers"]; + } + if (details.headers) { + details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ + name, + name.toLowerCase() === "authorization" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value + ])); + } + if ("retryOfRequestLogID" in details) { + if (details.retryOfRequestLogID) { + details.retryOf = details.retryOfRequestLogID; + } + delete details.retryOfRequestLogID; + } + return details; +}; -// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/parse.js -function parsePatch(uniDiff) { - const diffstr = uniDiff.split(/\n/), list = []; - let i = 0; - function parseIndex() { - const index = {}; - list.push(index); - while (i < diffstr.length) { - const line = diffstr[i]; - if (/^(---|\+\+\+|@@)\s/.test(line)) { - break; +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/parse.mjs +async function defaultParseResponse3(client, props) { + const { response, requestLogID, retryOfRequestLogID, startTime } = props; + const body = await (async () => { + if (response.status === 204) { + return null; + } + if (props.options.__binaryResponse) { + return response; + } + const contentType = response.headers.get("content-type"); + const mediaType = contentType?.split(";")[0]?.trim(); + const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json"); + if (isJSON) { + const contentLength = response.headers.get("content-length"); + if (contentLength === "0") { + return void 0; } - const headerMatch = /^(?:Index:|diff(?: -r \w+)+)\s+/.exec(line); - if (headerMatch) { - index.index = line.substring(headerMatch[0].length).trim(); + const json = await response.json(); + return json; + } + const text = await response.text(); + return text; + })(); + loggerFor3(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails3({ + retryOfRequestLogID, + url: response.url, + status: response.status, + body, + durationMs: Date.now() - startTime + })); + return body; +} + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/core/api-promise.mjs +var _APIPromise_client3; +var APIPromise3 = /* @__PURE__ */ (() => { + class APIPromise4 extends Promise { + constructor(client, responsePromise, parseResponse = defaultParseResponse3) { + super((resolve) => { + resolve(null); + }); + this.responsePromise = responsePromise; + this.parseResponse = parseResponse; + _APIPromise_client3.set(this, void 0); + __classPrivateFieldSet3(this, _APIPromise_client3, client, "f"); + } + _thenUnwrap(transform) { + return new APIPromise4(__classPrivateFieldGet3(this, _APIPromise_client3, "f"), this.responsePromise, async (client, props) => transform(await this.parseResponse(client, props), props)); + } + /** + * Gets the raw `Response` instance instead of parsing the response + * data. + * + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + asResponse() { + return this.responsePromise.then((p) => p.response); + } + /** + * Gets the parsed response data and the raw `Response` instance. + * + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + async withResponse() { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { data, response }; + } + parse() { + if (!this.parsedPromise) { + this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet3(this, _APIPromise_client3, "f"), data)); } - i++; + return this.parsedPromise; } - parseFileHeader(index); - parseFileHeader(index); - index.hunks = []; - while (i < diffstr.length) { - const line = diffstr[i]; - if (/^(Index:\s|diff\s|---\s|\+\+\+\s|===================================================================)/.test(line)) { - break; - } else if (/^@@/.test(line)) { - index.hunks.push(parseHunk()); - } else if (line) { - throw new Error("Unknown line " + (i + 1) + " " + JSON.stringify(line)); - } else { - i++; + then(onfulfilled, onrejected) { + return this.parse().then(onfulfilled, onrejected); + } + catch(onrejected) { + return this.parse().catch(onrejected); + } + finally(onfinally) { + return this.parse().finally(onfinally); + } + } + _APIPromise_client3 = /* @__PURE__ */ new WeakMap(); + return APIPromise4; +})(); + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/utils/env.mjs +var readEnv3 = (env) => { + if (typeof globalThis.process !== "undefined") { + return globalThis.process.env?.[env]?.trim() ?? void 0; + } + if (typeof globalThis.Deno !== "undefined") { + return globalThis.Deno.env?.get?.(env)?.trim(); + } + return void 0; +}; + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/client.mjs +var _BaseGitLab_instances; +var _BaseGitLab_encoder; +var _BaseGitLab_baseURLOverridden; +var BaseGitLab = /* @__PURE__ */ (() => { + class BaseGitLab2 { + /** + * API Client for interfacing with the GitLab API. + * + * @param {string | undefined} [opts.apiToken=process.env['GITLAB_API_TOKEN'] ?? undefined] + * @param {string} [opts.baseURL=process.env['GITLAB_BASE_URL'] ?? https://gitlab.com/api/v4] - Override the default base URL for the API. + * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. + * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. + */ + constructor({ baseURL = readEnv3("GITLAB_BASE_URL"), apiToken = readEnv3("GITLAB_API_TOKEN"), ...opts } = {}) { + _BaseGitLab_instances.add(this); + _BaseGitLab_encoder.set(this, void 0); + if (apiToken === void 0) { + throw new GitLabError("The GITLAB_API_TOKEN environment variable is missing or empty; either provide it, or instantiate the GitLab client with an apiToken option, like new GitLab({ apiToken: 'My API Token' })."); } + const options = { + apiToken, + ...opts, + baseURL: baseURL || `https://gitlab.com/api/v4` + }; + this.baseURL = options.baseURL; + this.timeout = options.timeout ?? BaseGitLab2.DEFAULT_TIMEOUT; + this.logger = options.logger ?? console; + const defaultLogLevel = "warn"; + this.logLevel = defaultLogLevel; + this.logLevel = parseLogLevel3(options.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel3(readEnv3("GITLAB_LOG"), "process.env['GITLAB_LOG']", this) ?? defaultLogLevel; + this.fetchOptions = options.fetchOptions; + this.maxRetries = options.maxRetries ?? 2; + this.fetch = options.fetch ?? getDefaultFetch3(); + __classPrivateFieldSet3(this, _BaseGitLab_encoder, FallbackEncoder3, "f"); + this._options = options; + this.apiToken = apiToken; } - } - function parseFileHeader(index) { - const fileHeaderMatch = /^(---|\+\+\+)\s+/.exec(diffstr[i]); - if (fileHeaderMatch) { - const prefix = fileHeaderMatch[1], data = diffstr[i].substring(3).trim().split(" ", 2), header = (data[1] || "").trim(); - let fileName = data[0].replace(/\\\\/g, "\\"); - if (fileName.startsWith('"') && fileName.endsWith('"')) { - fileName = fileName.substr(1, fileName.length - 2); - } - if (prefix === "---") { - index.oldFileName = fileName; - index.oldHeader = header; - } else { - index.newFileName = fileName; - index.newHeader = header; - } - i++; + /** + * Create a new client instance re-using the same options given to the current client with optional overriding. + */ + withOptions(options) { + const client = new this.constructor({ + ...this._options, + baseURL: this.baseURL, + maxRetries: this.maxRetries, + timeout: this.timeout, + logger: this.logger, + logLevel: this.logLevel, + fetch: this.fetch, + fetchOptions: this.fetchOptions, + apiToken: this.apiToken, + ...options + }); + return client; } - } - function parseHunk() { - var _a2; - const chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); - const hunk = { - oldStart: +chunkHeader[1], - oldLines: typeof chunkHeader[2] === "undefined" ? 1 : +chunkHeader[2], - newStart: +chunkHeader[3], - newLines: typeof chunkHeader[4] === "undefined" ? 1 : +chunkHeader[4], - lines: [] - }; - if (hunk.oldLines === 0) { - hunk.oldStart += 1; + /** + * Execute a GLQL (GitLab Query Language) query + */ + glql(body, options) { + return this.post("/glql", { body, ...options }); } - if (hunk.newLines === 0) { - hunk.newStart += 1; + /** + * This feature was introduced in GitLab 11.0. + */ + markdown(body, options) { + return this.post("/markdown", { body, ...options }); } - let addCount = 0, removeCount = 0; - for (; i < diffstr.length && (removeCount < hunk.oldLines || addCount < hunk.newLines || ((_a2 = diffstr[i]) === null || _a2 === void 0 ? void 0 : _a2.startsWith("\\"))); i++) { - const operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? " " : diffstr[i][0]; - if (operation === "+" || operation === "-" || operation === " " || operation === "\\") { - hunk.lines.push(diffstr[i]); - if (operation === "+") { - addCount++; - } else if (operation === "-") { - removeCount++; - } else if (operation === " ") { - addCount++; - removeCount++; - } - } else { - throw new Error(`Hunk at line ${chunkHeaderIndex + 1} contained invalid line ${diffstr[i]}`); - } + /** + * This feature was introduced in GitLab 17.5. \ + * This feature is currently in an experimental state. \ + * This feature is behind the `allow_organization_creation` feature flag. \ + * In GitLab 18.3, feature flag changed to `organization_switching`. + */ + organizations(body, options) { + return this.post("/organizations", multipartFormRequestOptions({ body, ...options }, this)); } - if (!addCount && hunk.newLines === 1) { - hunk.newLines = 0; + /** + * Return avatar url for a user + */ + retrieveAvatar(query, options) { + return this.get("/avatar", { query, ...options }); } - if (!removeCount && hunk.oldLines === 1) { - hunk.oldLines = 0; + /** + * Get a list of all deploy tokens across the GitLab instance. This endpoint + * requires administrator access. This feature was introduced in GitLab 12.9. + */ + retrieveDeployTokens(query = {}, options) { + return this.get("/deploy_tokens", { query, ...options }); } - if (addCount !== hunk.newLines) { - throw new Error("Added line count did not match for hunk at line " + (chunkHeaderIndex + 1)); + /** + * This feature was introduced in GitLab 17.9. It will be removed in 18.0. + */ + retrieveDiscoverCertBasedClusters(query, options) { + return this.get("/discover-cert-based-clusters", { query, ...options }); } - if (removeCount !== hunk.oldLines) { - throw new Error("Removed line count did not match for hunk at line " + (chunkHeaderIndex + 1)); + /** + * This feature was introduced in GitLab 9.3. + */ + retrieveEvents(query = {}, options) { + return this.get("/events", { query, ...options }); } - return hunk; - } - while (i < diffstr.length) { - parseIndex(); - } - return list; -} - -// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/util/distance-iterator.js -function distance_iterator_default(start, minLine, maxLine) { - let wantForward = true, backwardExhausted = false, forwardExhausted = false, localOffset = 1; - return function iterator() { - if (wantForward && !forwardExhausted) { - if (backwardExhausted) { - localOffset++; - } else { - wantForward = false; - } - if (start + localOffset <= maxLine) { - return start + localOffset; - } - forwardExhausted = true; + /** + * Get a list of all experiments. Each experiment has an enabled status that + * indicates whetherthe experiment is enabled globally, or only in specific + * contexts. + */ + retrieveExperiments(options) { + return this.get("/experiments", options); } - if (!backwardExhausted) { - if (!forwardExhausted) { - wantForward = true; - } - if (minLine <= start - localOffset) { - return start - localOffset++; - } - backwardExhausted = true; - return iterator(); + /** + * Get currently authenticated user's issues statistics + */ + retrieveIssuesStatistics(query = {}, options) { + return this.get("/issues_statistics", { + query, + ...options, + headers: buildHeaders3([{ Accept: "*/*" }, options?.headers]) + }); } - return void 0; - }; -} - -// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/apply.js -function applyPatch(source, patch, options = {}) { - let patches; - if (typeof patch === "string") { - patches = parsePatch(patch); - } else if (Array.isArray(patch)) { - patches = patch; - } else { - patches = [patch]; - } - if (patches.length > 1) { - throw new Error("applyPatch only works with a single input."); - } - return applyStructuredPatch(source, patches[0], options); -} -function applyStructuredPatch(source, patch, options = {}) { - if (options.autoConvertLineEndings || options.autoConvertLineEndings == null) { - if (hasOnlyWinLineEndings(source) && isUnix(patch)) { - patch = unixToWin(patch); - } else if (hasOnlyUnixLineEndings(source) && isWin(patch)) { - patch = winToUnix(patch); + /** + * Get a list of licenses + */ + retrieveLicenses(options) { + return this.get("/licenses", options); } - } - const lines = source.split("\n"), hunks = patch.hunks, compareLine = options.compareLine || ((lineNumber, line, operation, patchContent) => line === patchContent), fuzzFactor = options.fuzzFactor || 0; - let minLine = 0; - if (fuzzFactor < 0 || !Number.isInteger(fuzzFactor)) { - throw new Error("fuzzFactor must be a non-negative integer"); - } - if (!hunks.length) { - return source; - } - let prevLine = "", removeEOFNL = false, addEOFNL = false; - for (let i = 0; i < hunks[hunks.length - 1].lines.length; i++) { - const line = hunks[hunks.length - 1].lines[i]; - if (line[0] == "\\") { - if (prevLine[0] == "+") { - removeEOFNL = true; - } else if (prevLine[0] == "-") { - addEOFNL = true; - } + /** + * Get all merge requests the authenticated user has access to. By default it + * returns only merge requests created by the current user. To get all merge + * requests, use parameter `scope=all`. + */ + retrieveMergeRequests(query = {}, options) { + return this.get("/merge_requests", { query, ...options }); } - prevLine = line; - } - if (removeEOFNL) { - if (addEOFNL) { - if (!fuzzFactor && lines[lines.length - 1] == "") { - return false; - } - } else if (lines[lines.length - 1] == "") { - lines.pop(); - } else if (!fuzzFactor) { - return false; + /** + * This feature was introduced in GitLab 15.2. + */ + retrieveMetadata(options) { + return this.get("/metadata", options); + } + /** + * This feature was introduced in GitLab 10.5. + */ + retrieveSearch(query, options) { + return this.get("/search", { + query, + ...options, + headers: buildHeaders3([{ Accept: "*/*" }, options?.headers]) + }); } - } else if (addEOFNL) { - if (lines[lines.length - 1] != "") { - lines.push(""); - } else if (!fuzzFactor) { - return false; + /** + * Assigned open issues, assigned MRs and pending todos count + */ + retrieveUserCounts(options) { + return this.get("/user_counts", options); } - } - function applyHunk(hunkLines, toPos, maxErrors, hunkLinesI = 0, lastContextLineMatched = true, patchedLines = [], patchedLinesLength = 0) { - let nConsecutiveOldContextLines = 0; - let nextContextLineMustMatch = false; - for (; hunkLinesI < hunkLines.length; hunkLinesI++) { - const hunkLine = hunkLines[hunkLinesI], operation = hunkLine.length > 0 ? hunkLine[0] : " ", content = hunkLine.length > 0 ? hunkLine.substr(1) : hunkLine; - if (operation === "-") { - if (compareLine(toPos + 1, lines[toPos], operation, content)) { - toPos++; - nConsecutiveOldContextLines = 0; - } else { - if (!maxErrors || lines[toPos] == null) { - return null; - } - patchedLines[patchedLinesLength] = lines[toPos]; - return applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1); - } - } - if (operation === "+") { - if (!lastContextLineMatched) { - return null; - } - patchedLines[patchedLinesLength] = content; - patchedLinesLength++; - nConsecutiveOldContextLines = 0; - nextContextLineMustMatch = true; - } - if (operation === " ") { - nConsecutiveOldContextLines++; - patchedLines[patchedLinesLength] = lines[toPos]; - if (compareLine(toPos + 1, lines[toPos], operation, content)) { - patchedLinesLength++; - lastContextLineMatched = true; - nextContextLineMustMatch = false; - toPos++; - } else { - if (nextContextLineMustMatch || !maxErrors) { - return null; - } - return lines[toPos] && (applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI + 1, false, patchedLines, patchedLinesLength + 1) || applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1)) || applyHunk(hunkLines, toPos, maxErrors - 1, hunkLinesI + 1, false, patchedLines, patchedLinesLength); - } - } + /** + * This feature was introduced in GitLab 8.13 and deprecated in 15.5. We recommend + * you instead use the Metadata API. + */ + retrieveVersion(options) { + return this.get("/version", options); } - patchedLinesLength -= nConsecutiveOldContextLines; - toPos -= nConsecutiveOldContextLines; - patchedLines.length = patchedLinesLength; - return { - patchedLines, - oldLineLastI: toPos - 1 - }; - } - const resultLines = []; - let prevHunkOffset = 0; - for (let i = 0; i < hunks.length; i++) { - const hunk = hunks[i]; - let hunkResult; - const maxLine = lines.length - hunk.oldLines + fuzzFactor; - let toPos; - for (let maxErrors = 0; maxErrors <= fuzzFactor; maxErrors++) { - toPos = hunk.oldStart + prevHunkOffset - 1; - const iterator = distance_iterator_default(toPos, minLine, maxLine); - for (; toPos !== void 0; toPos = iterator()) { - hunkResult = applyHunk(hunk.lines, toPos, maxErrors); - if (hunkResult) { - break; - } - } - if (hunkResult) { - break; - } + defaultQuery() { + return this._options.defaultQuery; } - if (!hunkResult) { - return false; + validateHeaders({ values, nulls }) { + return; } - for (let i2 = minLine; i2 < toPos; i2++) { - resultLines.push(lines[i2]); + async authHeaders(opts) { + return buildHeaders3([{ Authorization: `Bearer ${this.apiToken}` }]); } - for (let i2 = 0; i2 < hunkResult.patchedLines.length; i2++) { - const line = hunkResult.patchedLines[i2]; - resultLines.push(line); + stringifyQuery(query) { + return stringify3(query, { arrayFormat: "comma" }); } - minLine = hunkResult.oldLineLastI + 1; - prevHunkOffset = toPos + 1 - hunk.oldStart; - } - for (let i = minLine; i < lines.length; i++) { - resultLines.push(lines[i]); - } - return resultLines.join("\n"); -} - -// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js -var INCLUDE_HEADERS = { - includeIndex: true, - includeUnderline: true, - includeFileHeaders: true -}; -function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { - let optionsObj; - if (!options) { - optionsObj = {}; - } else if (typeof options === "function") { - optionsObj = { callback: options }; - } else { - optionsObj = options; - } - if (typeof optionsObj.context === "undefined") { - optionsObj.context = 4; - } - const context = optionsObj.context; - if (optionsObj.newlineIsToken) { - throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions"); - } - if (!optionsObj.callback) { - return diffLinesResultToPatch(diffLines(oldStr, newStr, optionsObj)); - } else { - const { callback } = optionsObj; - diffLines(oldStr, newStr, Object.assign(Object.assign({}, optionsObj), { callback: (diff) => { - const patch = diffLinesResultToPatch(diff); - callback(patch); - } })); - } - function diffLinesResultToPatch(diff) { - if (!diff) { - return; + getUserAgent() { + return `${this.constructor.name}/JS ${VERSION3}`; } - diff.push({ value: "", lines: [] }); - function contextLines(lines) { - return lines.map(function(entry) { - return " " + entry; - }); + defaultIdempotencyKey() { + return `stainless-node-retry-${uuid43()}`; } - const hunks = []; - let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; - for (let i = 0; i < diff.length; i++) { - const current = diff[i], lines = current.lines || splitLines(current.value); - current.lines = lines; - if (current.added || current.removed) { - if (!oldRangeStart) { - const prev = diff[i - 1]; - oldRangeStart = oldLine; - newRangeStart = newLine; - if (prev) { - curRange = context > 0 ? contextLines(prev.lines.slice(-context)) : []; - oldRangeStart -= curRange.length; - newRangeStart -= curRange.length; - } - } - for (const line of lines) { - curRange.push((current.added ? "+" : "-") + line); - } - if (current.added) { - newLine += lines.length; - } else { - oldLine += lines.length; - } - } else { - if (oldRangeStart) { - if (lines.length <= context * 2 && i < diff.length - 2) { - for (const line of contextLines(lines)) { - curRange.push(line); - } - } else { - const contextSize = Math.min(lines.length, context); - for (const line of contextLines(lines.slice(0, contextSize))) { - curRange.push(line); - } - const hunk = { - oldStart: oldRangeStart, - oldLines: oldLine - oldRangeStart + contextSize, - newStart: newRangeStart, - newLines: newLine - newRangeStart + contextSize, - lines: curRange - }; - hunks.push(hunk); - oldRangeStart = 0; - newRangeStart = 0; - curRange = []; - } - } - oldLine += lines.length; - newLine += lines.length; - } + makeStatusError(status, error, message, headers) { + return APIError3.generate(status, error, message, headers); } - for (const hunk of hunks) { - for (let i = 0; i < hunk.lines.length; i++) { - if (hunk.lines[i].endsWith("\n")) { - hunk.lines[i] = hunk.lines[i].slice(0, -1); - } else { - hunk.lines.splice(i + 1, 0, "\\ No newline at end of file"); - i++; - } + buildURL(path7, query, defaultBaseURL) { + const baseURL = !__classPrivateFieldGet3(this, _BaseGitLab_instances, "m", _BaseGitLab_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL; + const url = isAbsoluteURL3(path7) ? new URL(path7) : new URL(baseURL + (baseURL.endsWith("/") && path7.startsWith("/") ? path7.slice(1) : path7)); + const defaultQuery = this.defaultQuery(); + if (!isEmptyObj3(defaultQuery)) { + query = { ...defaultQuery, ...query }; } + if (typeof query === "object" && query && !Array.isArray(query)) { + url.search = this.stringifyQuery(query); + } + return url.toString(); } - return { - oldFileName, - newFileName, - oldHeader, - newHeader, - hunks - }; - } -} -function formatPatch(patch, headerOptions) { - if (!headerOptions) { - headerOptions = INCLUDE_HEADERS; - } - if (Array.isArray(patch)) { - if (patch.length > 1 && !headerOptions.includeFileHeaders) { - throw new Error("Cannot omit file headers on a multi-file patch. (The result would be unparseable; how would a tool trying to apply the patch know which changes are to which file?)"); - } - return patch.map((p) => formatPatch(p, headerOptions)).join("\n"); - } - const ret = []; - if (headerOptions.includeIndex && patch.oldFileName == patch.newFileName) { - ret.push("Index: " + patch.oldFileName); - } - if (headerOptions.includeUnderline) { - ret.push("==================================================================="); - } - if (headerOptions.includeFileHeaders) { - ret.push("--- " + patch.oldFileName + (typeof patch.oldHeader === "undefined" ? "" : " " + patch.oldHeader)); - ret.push("+++ " + patch.newFileName + (typeof patch.newHeader === "undefined" ? "" : " " + patch.newHeader)); - } - for (let i = 0; i < patch.hunks.length; i++) { - const hunk = patch.hunks[i]; - if (hunk.oldLines === 0) { - hunk.oldStart -= 1; + /** + * Used as a callback for mutating the given `FinalRequestOptions` object. + */ + async prepareOptions(options) { } - if (hunk.newLines === 0) { - hunk.newStart -= 1; + /** + * Used as a callback for mutating the given `RequestInit` object. + * + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. + */ + async prepareRequest(request, { url, options }) { } - ret.push("@@ -" + hunk.oldStart + "," + hunk.oldLines + " +" + hunk.newStart + "," + hunk.newLines + " @@"); - for (const line of hunk.lines) { - ret.push(line); + get(path7, opts) { + return this.methodRequest("get", path7, opts); } - } - return ret.join("\n") + "\n"; -} -function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { - if (typeof options === "function") { - options = { callback: options }; - } - if (!(options === null || options === void 0 ? void 0 : options.callback)) { - const patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); - if (!patchObj) { - return; + post(path7, opts) { + return this.methodRequest("post", path7, opts); } - return formatPatch(patchObj, options === null || options === void 0 ? void 0 : options.headerOptions); - } else { - const { callback } = options; - structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, Object.assign(Object.assign({}, options), { callback: (patchObj) => { - if (!patchObj) { - callback(void 0); - } else { - callback(formatPatch(patchObj, options.headerOptions)); - } - } })); - } -} -function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { - return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); -} -function splitLines(text) { - const hasTrailingNl = text.endsWith("\n"); - const result = text.split("\n").map((line) => line + "\n"); - if (hasTrailingNl) { - result.pop(); - } else { - result.push(result.pop().slice(0, -1)); - } - return result; -} - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/tslib.mjs -function __classPrivateFieldSet3(receiver, state, value, kind, f) { - if (kind === "m") - throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) - throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) - throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; -} -function __classPrivateFieldGet3(receiver, state, kind, f) { - if (kind === "a" && !f) - throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) - throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -} - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/uuid.mjs -var uuid43 = function() { - const { crypto: crypto2 } = globalThis; - if (crypto2?.randomUUID) { - uuid43 = crypto2.randomUUID.bind(crypto2); - return crypto2.randomUUID(); - } - const u8 = new Uint8Array(1); - const randomByte = crypto2 ? () => crypto2.getRandomValues(u8)[0] : () => Math.random() * 255 & 255; - return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16)); -}; - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/errors.mjs -function isAbortError3(err) { - return typeof err === "object" && err !== null && // Spec-compliant fetch implementations - ("name" in err && err.name === "AbortError" || // Expo fetch - "message" in err && String(err.message).includes("FetchRequestCanceledException")); -} -var castToError3 = (err) => { - if (err instanceof Error) - return err; - if (typeof err === "object" && err !== null) { - try { - if (Object.prototype.toString.call(err) === "[object Error]") { - const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); - if (err.stack) - error.stack = err.stack; - if (err.cause && !error.cause) - error.cause = err.cause; - if (err.name) - error.name = err.name; - return error; - } - } catch { + patch(path7, opts) { + return this.methodRequest("patch", path7, opts); } - try { - return new Error(JSON.stringify(err)); - } catch { + put(path7, opts) { + return this.methodRequest("put", path7, opts); } - } - return new Error(err); -}; - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/core/error.mjs -var StainlessError = class extends Error { -}; -var APIError3 = class _APIError extends StainlessError { - constructor(status, error, message, headers) { - super(`${_APIError.makeMessage(status, error, message)}`); - this.status = status; - this.headers = headers; - this.error = error; - } - static makeMessage(status, error, message) { - const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message; - if (status && msg) { - return `${status} ${msg}`; + delete(path7, opts) { + return this.methodRequest("delete", path7, opts); } - if (status) { - return `${status} status code (no body)`; + methodRequest(method, path7, opts) { + return this.request(Promise.resolve(opts).then((opts2) => { + return { method, path: path7, ...opts2 }; + })); } - if (msg) { - return msg; + request(options, remainingRetries = null) { + return new APIPromise3(this, this.makeRequest(options, remainingRetries, void 0)); } - return "(no status code or body)"; - } - static generate(status, errorResponse, message, headers) { - if (!status || !headers) { - return new APIConnectionError3({ message, cause: castToError3(errorResponse) }); + async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { + const options = await optionsInput; + const maxRetries = options.maxRetries ?? this.maxRetries; + if (retriesRemaining == null) { + retriesRemaining = maxRetries; + } + await this.prepareOptions(options); + const { req, url, timeout } = await this.buildRequest(options, { + retryCount: maxRetries - retriesRemaining + }); + await this.prepareRequest(req, { url, options }); + const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0"); + const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`; + const startTime = Date.now(); + loggerFor3(this).debug(`[${requestLogID}] sending request`, formatRequestDetails3({ + retryOfRequestLogID, + method: options.method, + url, + options, + headers: req.headers + })); + if (options.signal?.aborted) { + throw new APIUserAbortError3(); + } + const controller = new AbortController(); + const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError3); + const headersTime = Date.now(); + if (response instanceof globalThis.Error) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + if (options.signal?.aborted) { + throw new APIUserAbortError3(); + } + const isTimeout = isAbortError3(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : "")); + if (retriesRemaining) { + loggerFor3(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`); + loggerFor3(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails3({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); + } + loggerFor3(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`); + loggerFor3(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails3({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + if (isTimeout) { + throw new APIConnectionTimeoutError3(); + } + throw new APIConnectionError3({ cause: response }); + } + const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`; + if (!response.ok) { + const shouldRetry = await this.shouldRetry(response); + if (retriesRemaining && shouldRetry) { + const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`; + await CancelReadableStream3(response.body); + loggerFor3(this).info(`${responseInfo} - ${retryMessage2}`); + loggerFor3(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails3({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); + } + const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; + loggerFor3(this).info(`${responseInfo} - ${retryMessage}`); + const errText = await response.text().catch((err2) => castToError3(err2).message); + const errJSON = safeJSON3(errText); + const errMessage = errJSON ? void 0 : errText; + loggerFor3(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails3({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + message: errMessage, + durationMs: Date.now() - startTime + })); + const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); + throw err; + } + loggerFor3(this).info(responseInfo); + loggerFor3(this).debug(`[${requestLogID}] response start`, formatRequestDetails3({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; + } + async fetchWithTimeout(url, init, ms, controller) { + const { signal, method, ...options } = init || {}; + const abort = this._makeAbort(controller); + if (signal) + signal.addEventListener("abort", abort, { once: true }); + const timeout = setTimeout(abort, ms); + const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body; + const fetchOptions = { + signal: controller.signal, + ...isReadableBody ? { duplex: "half" } : {}, + method: "GET", + ...options + }; + if (method) { + fetchOptions.method = method.toUpperCase(); + } + try { + return await this.fetch.call(void 0, url, fetchOptions); + } finally { + clearTimeout(timeout); + } + } + async shouldRetry(response) { + const shouldRetryHeader = response.headers.get("x-should-retry"); + if (shouldRetryHeader === "true") + return true; + if (shouldRetryHeader === "false") + return false; + if (response.status === 408) + return true; + if (response.status === 409) + return true; + if (response.status === 429) + return true; + if (response.status >= 500) + return true; + return false; } - const error = errorResponse; - if (status === 400) { - return new BadRequestError3(status, error, message, headers); + async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { + let timeoutMillis; + const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms"); + if (retryAfterMillisHeader) { + const timeoutMs = parseFloat(retryAfterMillisHeader); + if (!Number.isNaN(timeoutMs)) { + timeoutMillis = timeoutMs; + } + } + const retryAfterHeader = responseHeaders?.get("retry-after"); + if (retryAfterHeader && !timeoutMillis) { + const timeoutSeconds = parseFloat(retryAfterHeader); + if (!Number.isNaN(timeoutSeconds)) { + timeoutMillis = timeoutSeconds * 1e3; + } else { + timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); + } + } + if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1e3)) { + const maxRetries = options.maxRetries ?? this.maxRetries; + timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + } + await sleep3(timeoutMillis); + return this.makeRequest(options, retriesRemaining - 1, requestLogID); } - if (status === 401) { - return new AuthenticationError3(status, error, message, headers); + calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { + const initialRetryDelay = 0.5; + const maxRetryDelay = 8; + const numRetries = maxRetries - retriesRemaining; + const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); + const jitter = 1 - Math.random() * 0.25; + return sleepSeconds * jitter * 1e3; } - if (status === 403) { - return new PermissionDeniedError3(status, error, message, headers); + async buildRequest(inputOptions, { retryCount = 0 } = {}) { + const options = { ...inputOptions }; + const { method, path: path7, query, defaultBaseURL } = options; + const url = this.buildURL(path7, query, defaultBaseURL); + if ("timeout" in options) + validatePositiveInteger3("timeout", options.timeout); + options.timeout = options.timeout ?? this.timeout; + const { bodyHeaders, body } = this.buildBody({ options }); + const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); + const req = { + method, + headers: reqHeaders, + ...options.signal && { signal: options.signal }, + ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" }, + ...body && { body }, + ...this.fetchOptions ?? {}, + ...options.fetchOptions ?? {} + }; + return { req, url, timeout: options.timeout }; } - if (status === 404) { - return new NotFoundError3(status, error, message, headers); + async buildHeaders({ options, method, bodyHeaders, retryCount }) { + let idempotencyHeaders = {}; + if (this.idempotencyHeader && method !== "get") { + if (!options.idempotencyKey) + options.idempotencyKey = this.defaultIdempotencyKey(); + idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; + } + const headers = buildHeaders3([ + idempotencyHeaders, + { + Accept: "application/json", + "User-Agent": this.getUserAgent(), + "X-Stainless-Retry-Count": String(retryCount), + ...options.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options.timeout / 1e3)) } : {}, + ...getPlatformHeaders3() + }, + await this.authHeaders(options), + this._options.defaultHeaders, + bodyHeaders, + options.headers + ]); + this.validateHeaders(headers); + return headers.values; } - if (status === 409) { - return new ConflictError3(status, error, message, headers); + _makeAbort(controller) { + return () => controller.abort(); } - if (status === 422) { - return new UnprocessableEntityError3(status, error, message, headers); + buildBody({ options: { body, headers: rawHeaders } }) { + if (!body) { + return { bodyHeaders: void 0, body: void 0 }; + } + const headers = buildHeaders3([rawHeaders]); + if ( + // Pass raw type verbatim + ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && // Preserve legacy string encoding behavior for now + headers.values.has("content-type") || // `Blob` is superset of `File` + globalThis.Blob && body instanceof globalThis.Blob || // `FormData` -> `multipart/form-data` + body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded` + body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`) + globalThis.ReadableStream && body instanceof globalThis.ReadableStream + ) { + return { bodyHeaders: void 0, body }; + } else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) { + return { bodyHeaders: void 0, body: ReadableStreamFrom3(body) }; + } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") { + return { + bodyHeaders: { "content-type": "application/x-www-form-urlencoded" }, + body: this.stringifyQuery(body) + }; + } else { + return __classPrivateFieldGet3(this, _BaseGitLab_encoder, "f").call(this, { body, headers }); + } } - if (status === 429) { - return new RateLimitError3(status, error, message, headers); + } + _BaseGitLab_encoder = /* @__PURE__ */ new WeakMap(), _BaseGitLab_instances = /* @__PURE__ */ new WeakSet(), _BaseGitLab_baseURLOverridden = function _BaseGitLab_baseURLOverridden2() { + return this.baseURL !== "https://gitlab.com/api/v4"; + }; + BaseGitLab2.DEFAULT_TIMEOUT = 6e4; + return BaseGitLab2; +})(); + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/tree-shakable.mjs +function createClient2(options) { + const client = new BaseGitLab(options); + for (const ResourceClass of options.resources) { + const resourceInstance = new ResourceClass(client); + let object = client; + for (const part of ResourceClass._key.slice(0, -1)) { + if (hasOwn3(object, part)) { + object = object[part]; + } else { + Object.defineProperty(object, part, { + value: object = {}, + configurable: true, + enumerable: true, + writable: true + }); + } } - if (status >= 500) { - return new InternalServerError3(status, error, message, headers); + const name = ResourceClass._key.at(-1); + if (!hasOwn3(object, name)) { + Object.defineProperty(object, name, { + value: resourceInstance, + configurable: true, + enumerable: true, + writable: true + }); + } else { + if (object[name] instanceof APIResource3) { + throw new TypeError(`Resource at ${ResourceClass._key.join(".")} already exists!`); + } else { + object[name] = Object.assign(resourceInstance, object[name]); + } } - return new _APIError(status, error, message, headers); - } -}; -var APIUserAbortError3 = class extends APIError3 { - constructor({ message } = {}) { - super(void 0, void 0, message || "Request was aborted.", void 0); - } -}; -var APIConnectionError3 = class extends APIError3 { - constructor({ message, cause }) { - super(void 0, void 0, message || "Connection error.", void 0); - if (cause) - this.cause = cause; - } -}; -var APIConnectionTimeoutError3 = class extends APIConnectionError3 { - constructor({ message } = {}) { - super({ message: message ?? "Request timed out." }); } -}; -var BadRequestError3 = class extends APIError3 { -}; -var AuthenticationError3 = class extends APIError3 { -}; -var PermissionDeniedError3 = class extends APIError3 { -}; -var NotFoundError3 = class extends APIError3 { -}; -var ConflictError3 = class extends APIError3 { -}; -var UnprocessableEntityError3 = class extends APIError3 { -}; -var RateLimitError3 = class extends APIError3 { -}; -var InternalServerError3 = class extends APIError3 { -}; + return client; +} -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/values.mjs -var startsWithSchemeRegexp3 = /^[a-z][a-z0-9+.-]*:/i; -var isAbsoluteURL3 = (url) => { - return startsWithSchemeRegexp3.test(url); -}; -var isArray3 = (val) => (isArray3 = Array.isArray, isArray3(val)); -var isReadonlyArray3 = isArray3; -function maybeObj2(x) { - if (typeof x !== "object") { - return {}; +// src/compat/gitlab/context.ts +var cachedContext2; +function getGitLabContext() { + if (cachedContext2) { + return cachedContext2; } - return x ?? {}; -} -function isEmptyObj3(obj) { - if (!obj) - return true; - for (const _k in obj) - return false; - return true; -} -function hasOwn3(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} -var validatePositiveInteger3 = (name, n) => { - if (typeof n !== "number" || !Number.isInteger(n)) { - throw new StainlessError(`${name} must be an integer`); + const owner = process.env.CI_PROJECT_NAMESPACE; + const repo = process.env.CI_PROJECT_NAME; + const runURL = process.env.CI_JOB_URL; + const projectID = process.env.CI_PROJECT_ID; + if (!owner || !repo || !runURL || !projectID) { + throw new Error( + "Expected env vars CI_PROJECT_NAMESPACE, CI_PROJECT_NAME, CI_JOB_URL, and CI_PROJECT_ID to be set." + ); } - if (n < 0) { - throw new StainlessError(`${name} must be a positive integer`); + const host = process.env.CI_SERVER_URL || "https://gitlab.com"; + const apiURL = process.env.CI_API_V4_URL || `${host}/api/v4`; + const maybePRNumber = parseInt( + process.env.CI_MERGE_REQUEST_IID || process.env.MR_NUMBER || "", + 10 + ); + const defaultBranch = process.env.CI_DEFAULT_BRANCH || null; + const prNumber = Number.isInteger(maybePRNumber) ? maybePRNumber : null; + const refName = process.env.CI_COMMIT_REF_NAME || null; + const sha = process.env.CI_COMMIT_SHA || null; + cachedContext2 = { + provider: "gitlab", + host, + owner, + repo, + urls: { api: apiURL, run: runURL }, + names: { ci: "GitLab CI", pr: "MR", provider: "GitLab" }, + defaultBranch, + prNumber, + projectID, + refName, + sha + }; + logger.debug("GitLab context", cachedContext2); + return cachedContext2; +} + +// src/compat/gitlab/api.ts +var GitLabClient = class { + client; + constructor(token) { + this.client = createClient2({ + apiToken: token, + baseURL: getGitLabContext().urls.api, + resources: [BaseCommits3, BaseMergeRequests, BaseNotes2], + logLevel: "warn", + logger + }); } - return n; -}; -var safeJSON3 = (text) => { - try { - return JSON.parse(text); - } catch (err) { - return void 0; + async listComments(prNumber) { + const comments = await this.client.projects.mergeRequests.notes.list(prNumber, { id: getGitLabContext().projectID }).then((data) => Array.isArray(data) ? data : [data]).catch((err) => { + if (err instanceof APIError3 && err.status === 404) { + return []; + } + throw err; + }); + return comments.map((c) => ({ id: c.id, body: c.body ?? "" })); } -}; - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/sleep.mjs -var sleep3 = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/version.mjs -var VERSION3 = "0.5.0"; - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/detect-platform.mjs -function getDetectedPlatform3() { - if (typeof Deno !== "undefined" && Deno.build != null) { - return "deno"; + async createComment(prNumber, props) { + const data = await this.client.projects.mergeRequests.notes.create( + prNumber, + { ...props, id: getGitLabContext().projectID } + ); + return { id: data.id, body: data.body }; } - if (typeof EdgeRuntime !== "undefined") { - return "edge"; + async updateComment(prNumber, props) { + const data = await this.client.projects.mergeRequests.notes.update( + props.id, + { ...props, id: getGitLabContext().projectID, noteable_id: prNumber } + ); + return { id: data.id, body: data.body }; } - if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") { - return "node"; + async getPullRequest(number) { + let mergeRequest = null; + let attempts = 0; + while (attempts++ < 3) { + mergeRequest = await this.client.projects.mergeRequests.retrieve(number, { + id: getGitLabContext().projectID + }); + if (mergeRequest?.diff_refs?.start_sha && mergeRequest?.diff_refs?.head_sha) { + return { + number: mergeRequest.iid, + state: mergeRequest.state === "opened" ? "open" : mergeRequest.state === "locked" ? "closed" : mergeRequest.state, + title: mergeRequest.title, + base_sha: mergeRequest.diff_refs.start_sha, + base_ref: mergeRequest.target_branch, + head_sha: mergeRequest.diff_refs.head_sha, + head_ref: mergeRequest.source_branch, + merge_commit_sha: mergeRequest.merge_commit_sha || mergeRequest.squash_commit_sha || null + }; + } + await new Promise((resolve) => { + setTimeout(() => resolve(), 1e3 * (2 ** attempts + Math.random())); + }); + } + logger.warn( + `Failed to find get diff_refs for merge request after ${attempts} attempts`, + { mergeRequestIID: number } + ); + return null; } - return "unknown"; -} -var getPlatformProperties3 = () => { - const detectedPlatform = getDetectedPlatform3(); - if (detectedPlatform === "deno") { - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION3, - "X-Stainless-OS": normalizePlatform3(Deno.build.os), - "X-Stainless-Arch": normalizeArch3(Deno.build.arch), - "X-Stainless-Runtime": "deno", - "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown" - }; + async getPullRequestForCommit(sha) { + const mergeRequests = await this.client.projects.repository.commits.retrieveMergeRequests(sha, { + id: getGitLabContext().projectID + }).then( + (data) => ( + // The OAS claims it's a single object, but the docs claim it's an + // array? Just handle both. + (Array.isArray(data) ? data : [data]).filter( + (c) => c.state !== "closed" && c.state !== "locked" + ) + ) + ).catch((err) => { + if (err instanceof APIError3 && (err.status === 401 || err.status === 403 || err.status === 404)) { + return []; + } + throw err; + }); + if (mergeRequests.length === 0) { + return null; + } + if (mergeRequests.length > 1) { + logger.warn( + `Multiple merge requests found for commit; only using first.`, + { commit: sha, mergeRequests: mergeRequests.map((c) => c.iid) } + ); + } + const mergeRequestIID = mergeRequests[0].iid; + const mergeRequest = await this.getPullRequest(mergeRequestIID); + return mergeRequest; } - if (typeof EdgeRuntime !== "undefined") { - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION3, - "X-Stainless-OS": "Unknown", - "X-Stainless-Arch": `other:${EdgeRuntime}`, - "X-Stainless-Runtime": "edge", - "X-Stainless-Runtime-Version": globalThis.process.version - }; +}; +var cachedClient2; +function getGitLabClient() { + if (cachedClient2 !== void 0) { + return cachedClient2; } - if (detectedPlatform === "node") { - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION3, - "X-Stainless-OS": normalizePlatform3(globalThis.process.platform ?? "unknown"), - "X-Stainless-Arch": normalizeArch3(globalThis.process.arch ?? "unknown"), - "X-Stainless-Runtime": "node", - "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown" - }; + const token = getInput("GITLAB_TOKEN"); + if (token?.startsWith("$")) { + throw new Error( + `Input GITLAB_TOKEN starts with '$'; expected token to start with 'gl'. Does the CI have access to the variable?` + ); } - const browserInfo = getBrowserInfo3(); - if (browserInfo) { - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION3, - "X-Stainless-OS": "Unknown", - "X-Stainless-Arch": "unknown", - "X-Stainless-Runtime": `browser:${browserInfo.browser}`, - "X-Stainless-Runtime-Version": browserInfo.version - }; + if (token) { + cachedClient2 = new GitLabClient(token); + } else { + logger.info("No GitLab token found in input 'GITLAB_TOKEN'."); + cachedClient2 = null; } - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION3, - "X-Stainless-OS": "Unknown", - "X-Stainless-Arch": "unknown", - "X-Stainless-Runtime": "unknown", - "X-Stainless-Runtime-Version": "unknown" - }; -}; -function getBrowserInfo3() { - if (typeof navigator === "undefined" || !navigator) { - return null; + return cachedClient2; +} + +// src/compat/api.ts +function api(options) { + let client; + switch (getProvider()) { + case "github": { + client = getGitHubClient(); + break; + } + case "gitlab": { + client = getGitLabClient(); + break; + } } - const browserPatterns = [ - { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ } - ]; - for (const { key, pattern } of browserPatterns) { - const match = pattern.exec(navigator.userAgent); - if (match) { - const major = match[1] || 0; - const minor = match[2] || 0; - const patch = match[3] || 0; - return { browser: key, version: `${major}.${minor}.${patch}` }; + if (!client) { + if (options?.optional) { + return null; + } else { + throw new Error("Failed to get API client."); } } - return null; + return client; } -var normalizeArch3 = (arch) => { - if (arch === "x32") - return "x32"; - if (arch === "x86_64" || arch === "x64") - return "x64"; - if (arch === "arm") - return "arm"; - if (arch === "aarch64" || arch === "arm64") - return "arm64"; - if (arch) - return `other:${arch}`; - return "unknown"; -}; -var normalizePlatform3 = (platform) => { - platform = platform.toLowerCase(); - if (platform.includes("ios")) - return "iOS"; - if (platform === "android") - return "Android"; - if (platform === "darwin") - return "MacOS"; - if (platform === "win32") - return "Windows"; - if (platform === "freebsd") - return "FreeBSD"; - if (platform === "openbsd") - return "OpenBSD"; - if (platform === "linux") - return "Linux"; - if (platform) - return `Other:${platform}`; - return "Unknown"; -}; -var _platformHeaders3; -var getPlatformHeaders3 = () => { - return _platformHeaders3 ?? (_platformHeaders3 = getPlatformProperties3()); -}; -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/shims.mjs -function getDefaultFetch3() { - if (typeof fetch !== "undefined") { - return fetch; +// src/compat/context.ts +function ctx() { + switch (getProvider()) { + case "github": { + return getGitHubContext(); + } + case "gitlab": { + return getGitLabContext(); + } } - throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Stainless({ fetch })` or polyfill the global, `globalThis.fetch = fetch`"); } -function makeReadableStream3(...args) { - const ReadableStream = globalThis.ReadableStream; - if (typeof ReadableStream === "undefined") { - throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`"); + +// src/compat/output.ts +var crypto = __toESM(require("node:crypto")); +var fs2 = __toESM(require("node:fs")); +function setOutput(name, value) { + if (getProvider() === "gitlab") return; + const stringified = value === null || value === void 0 ? "" : typeof value === "string" ? value : JSON.stringify(value); + const filePath = process.env["GITHUB_OUTPUT"]; + if (filePath && fs2.existsSync(filePath)) { + const delimiter = `ghadelimiter_${crypto.randomUUID()}`; + fs2.appendFileSync( + filePath, + `${name}<<${delimiter} +${stringified} +${delimiter} +`, + "utf-8" + ); + } else { + process.stdout.write(` +::set-output name=${name}::${stringified} +`); } - return new ReadableStream(...args); } -function ReadableStreamFrom3(iterable) { - let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); - return makeReadableStream3({ - start() { - }, - async pull(controller) { - const { done, value } = await iter.next(); - if (done) { - controller.close(); - } else { - controller.enqueue(value); - } - }, - async cancel() { - await iter.return?.(); - } + +// src/compat/index.ts +async function getStainlessAuth() { + const apiKey = getInput("stainless_api_key", { + required: getProvider() === "gitlab" }); + if (apiKey) { + logger.debug("Authenticating with provided Stainless API key"); + return { + key: apiKey, + expiresAt: null + }; + } + logger.debug("Authenticating with GitHub OIDC"); + const requestUrl = process.env.ACTIONS_ID_TOKEN_REQUEST_URL; + const requestToken = process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN; + if (!requestUrl || !requestToken) { + throw new Error( + `Failed to authenticate with GitHub OIDC. Make sure your workflow has 'id-token: write' permission and that you have the Stainless GitHub App installed: https://www.stainless.com/docs/guides/publish/#install-the-stainless-github-app` + ); + } + try { + const response = await fetch(`${requestUrl}&audience=api.stainless.com`, { + headers: { Authorization: `Bearer ${requestToken}` } + }); + if (!response.ok) { + throw new Error(`HTTP ${response.status}: ${await response.text()}`); + } + const data = await response.json(); + if (!data.value) { + throw new Error("No token in OIDC response"); + } + return { + key: data.value, + expiresAt: Date.now() + 300 * 1e3 + }; + } catch (error) { + throw new Error( + `Failed to authenticate with GitHub OIDC. Make sure your workflow has 'id-token: write' permission and that you have the Stainless GitHub App installed: https://www.stainless.com/docs/guides/publish/#install-the-stainless-github-app. Error: ${error}` + ); + } } -async function CancelReadableStream3(stream) { - if (stream === null || typeof stream !== "object") - return; - if (stream[Symbol.asyncIterator]) { - await stream[Symbol.asyncIterator]().return?.(); - return; + +// src/merge.run.ts +var fs5 = __toESM(require("node:fs")); + +// src/commitMessage.ts +var CONVENTIONAL_COMMIT_REGEX = new RegExp( + /^(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test)(\(.*\))?(!?): .*$/m +); +function makeCommitMessageConventional(message) { + if (message && !CONVENTIONAL_COMMIT_REGEX.test(message)) { + logger.warn( + `Commit message "${message}" is not in Conventional Commits format: https://www.conventionalcommits.org/en/v1.0.0/. Prepending "feat:" and using anyway.` + ); + return `feat: ${message}`; } - const reader = stream.getReader(); - const cancelPromise = reader.cancel(); - reader.releaseLock(); - await cancelPromise; + return message; } -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/request-options.mjs -var FallbackEncoder3 = ({ headers, body }) => { - return { - bodyHeaders: { - "content-type": "application/json" - }, - body: JSON.stringify(body) - }; +// src/markdown.ts +var import_ts_dedent = __toESM(require_dist()); +var Symbol2 = { + Bulb: "\u{1F4A1}", + Construction: "\u{1F6A7}", + Exclamation: "\u2757", + Eyes: "\u{1F440}", + GreenSquare: "\u{1F7E9}", + HeavyAsterisk: "\u2731", + HourglassFlowingSand: "\u23F3", + MiddleDot: "\xB7", + RedSquare: "\u{1F7E5}", + RightwardsArrow: "\u2192", + Skipped: "\u23ED\uFE0F", + SpeechBalloon: "\u{1F4AC}", + Warning: "\u26A0\uFE0F", + WhiteCheckMark: "\u2705", + WhiteLargeSquare: "\u2B1C", + Zap: "\u26A1" }; +var Bold = (content) => `${content}`; +var CodeInline = (content) => `${content}`; +var Comment = (content) => ``; +var Italic = (content) => `${content}`; +function Dedent(templ, ...args) { + return (0, import_ts_dedent.dedent)(templ, ...args).trim().replaceAll(/\n\s*\n/gi, "\n\n"); +} +var Blockquote = (content) => Dedent` +
-// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/qs/formats.mjs -var default_format3 = "RFC3986"; -var default_formatter3 = (v) => String(v); -var formatters3 = { - RFC1738: (v) => String(v).replace(/%20/g, "+"), - RFC3986: default_formatter3 + ${content} + +
+ `; +var CodeBlock = (props) => { + const delimiter = "```"; + const content = typeof props === "string" ? props : props.content; + const language = typeof props === "string" ? "" : props.language; + return Dedent` + ${delimiter}${language} + ${content} + ${delimiter} + `; }; -var RFC17383 = "RFC1738"; +var Details = ({ + summary, + body, + indent = true, + open = false +}) => { + return Dedent` + + ${summary} -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/qs/utils.mjs -var has3 = (obj, key) => (has3 = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has3(obj, key)); -var hex_table3 = /* @__PURE__ */ (() => { - const array = []; - for (let i = 0; i < 256; ++i) { - array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase()); - } - return array; -})(); -var limit3 = 1024; -var encode3 = (str, _defaultEncoder, charset, _kind, format) => { - if (str.length === 0) { - return str; - } - let string = str; - if (typeof str === "symbol") { - string = Symbol.prototype.toString.call(str); - } else if (typeof str !== "string") { - string = String(str); - } - if (charset === "iso-8859-1") { - return escape(string).replace(/%u[0-9a-f]{4}/gi, function($0) { - return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; - }); - } - let out = ""; - for (let j = 0; j < string.length; j += limit3) { - const segment = string.length >= limit3 ? string.slice(j, j + limit3) : string; - const arr = []; - for (let i = 0; i < segment.length; ++i) { - let c = segment.charCodeAt(i); - if (c === 45 || // - - c === 46 || // . - c === 95 || // _ - c === 126 || // ~ - c >= 48 && c <= 57 || // 0-9 - c >= 65 && c <= 90 || // a-z - c >= 97 && c <= 122 || // A-Z - format === RFC17383 && (c === 40 || c === 41)) { - arr[arr.length] = segment.charAt(i); - continue; - } - if (c < 128) { - arr[arr.length] = hex_table3[c]; - continue; - } - if (c < 2048) { - arr[arr.length] = hex_table3[192 | c >> 6] + hex_table3[128 | c & 63]; - continue; - } - if (c < 55296 || c >= 57344) { - arr[arr.length] = hex_table3[224 | c >> 12] + hex_table3[128 | c >> 6 & 63] + hex_table3[128 | c & 63]; - continue; + ${indent ? Blockquote(body) : body} + + + `; +}; +var Heading = (content) => `

${content}

`; +var Link = ({ text, href }) => `${text}`; +var Rule = () => `
`; + +// src/outcomes.ts +var ASSUME_PENDING_CHECKS_SKIPPED_AFTER_SECS = 60; +var FailRunOn = [ + "never", + "fatal", + "error", + "warning", + "note" +]; +var OutcomeConclusion = [...FailRunOn, "success"]; +function shouldFailRun({ + failRunOn, + outcomes, + baseOutcomes +}) { + const failures = Object.entries(outcomes).flatMap(([language, outcome]) => { + const categorized = categorizeOutcome({ + outcome, + baseOutcome: baseOutcomes?.[language] + }); + if (categorized.isPending) { + return []; + } + const { severity, isRegression, description } = categorized; + const didFail = isRegression !== false && severity && OutcomeConclusion.indexOf(severity) <= OutcomeConclusion.indexOf(failRunOn); + return didFail ? [ + { + language, + reason: getReason({ + description, + isRegression + }) } - i += 1; - c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023); - arr[arr.length] = hex_table3[240 | c >> 18] + hex_table3[128 | c >> 12 & 63] + hex_table3[128 | c >> 6 & 63] + hex_table3[128 | c & 63]; + ] : []; + }); + if (failures.length > 0) { + logger.warn("The following languages did not build successfully:"); + for (const { language, reason } of failures) { + logger.warn(` ${language}: ${reason}`); } - out += arr.join(""); - } - return out; -}; -function is_buffer3(obj) { - if (!obj || typeof obj !== "object") { return false; } - return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); + return true; } -function maybe_map3(val, fn) { - if (isArray3(val)) { - const mapped = []; - for (let i = 0; i < val.length; i += 1) { - mapped.push(fn(val[i])); - } - return mapped; +function categorizeOutcome({ + outcome, + baseOutcome +}) { + const baseConclusion = baseOutcome?.commit?.conclusion; + const headConclusion = outcome.commit?.conclusion; + if (!headConclusion || baseOutcome && !baseConclusion) { + return { isPending: true }; } - return fn(val); -} - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/qs/stringify.mjs -var array_prefix_generators3 = { - brackets(prefix) { - return String(prefix) + "[]"; - }, - comma: "comma", - indices(prefix, key) { - return String(prefix) + "[" + key + "]"; - }, - repeat(prefix) { - return String(prefix); + const baseChecks = baseOutcome && baseOutcome.commit?.commit ? getChecks(baseOutcome) : {}; + const headChecks = outcome.commit?.commit ? getChecks(outcome) : {}; + if ([...Object.values(headChecks), ...Object.values(baseChecks)].some( + (check) => check && check.status !== "completed" + )) { + return { isPending: true }; } -}; -var push_to_array3 = function(arr, value_or_array) { - Array.prototype.push.apply(arr, isArray3(value_or_array) ? value_or_array : [value_or_array]); -}; -var toISOString3; -var defaults3 = { - addQueryPrefix: false, - allowDots: false, - allowEmptyArrays: false, - arrayFormat: "indices", - charset: "utf-8", - charsetSentinel: false, - delimiter: "&", - encode: true, - encodeDotInKeys: false, - encoder: encode3, - encodeValuesOnly: false, - format: default_format3, - formatter: default_formatter3, - /** @deprecated */ - indices: false, - serializeDate(date) { - return (toISOString3 ?? (toISOString3 = Function.prototype.call.bind(Date.prototype.toISOString)))(date); - }, - skipNulls: false, - strictNullHandling: false -}; -function is_non_nullish_primitive3(v) { - return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint"; -} -var sentinel3 = {}; -function inner_stringify3(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { - let obj = object; - let tmp_sc = sideChannel; - let step = 0; - let find_flag = false; - while ((tmp_sc = tmp_sc.get(sentinel3)) !== void 0 && !find_flag) { - const pos = tmp_sc.get(object); - step += 1; - if (typeof pos !== "undefined") { - if (pos === step) { - throw new RangeError("Cyclic object value"); - } else { - find_flag = true; + const newDiagnostics = sortDiagnostics( + baseOutcome ? getNewDiagnostics(outcome.diagnostics, baseOutcome.diagnostics) : outcome.diagnostics + ); + const conclusions = { + fatal: [ + "fatal", + "payment_required", + "timed_out", + "upstream_merge_conflict", + "version_bump" + ], + conflict: ["merge_conflict"], + diagnostic: ["error", "warning", "note"], + success: ["success", "noop", "cancelled"] + }; + const checks = getNewChecks(headChecks, baseChecks); + const checkFailures = CheckType.filter( + (checkType) => checks[checkType] && checks[checkType].status === "completed" && ["failure", "timed_out"].includes(checks[checkType].completed.conclusion) + ); + if (headConclusion === "timed_out" || baseConclusion === "timed_out") { + return { + isPending: false, + conclusion: "timed_out", + severity: "fatal", + description: "timed out before completion", + isRegression: null + }; + } + if (conclusions.fatal.includes(headConclusion)) { + return { + isPending: false, + conclusion: "fatal", + severity: "fatal", + description: `had a "${headConclusion}" conclusion, and no code was generated`, + isRegression: baseConclusion ? conclusions.fatal.includes(baseConclusion) ? false : true : null + }; + } + if (baseConclusion && conclusions.fatal.includes(baseConclusion)) { + return { + isPending: false, + conclusion: headConclusion, + severity: null, + description: `had a "${baseOutcome?.commit?.conclusion}" conclusion in the base build, which improved to "${headConclusion}"`, + isRegression: false + }; + } + if (conclusions.diagnostic.includes(headConclusion) || newDiagnostics.length > 0 || checkFailures.length > 0) { + const categoryOutcome = conclusions.diagnostic.includes(headConclusion) ? { + severity: headConclusion, + description: `had at least one "${headConclusion}" diagnostic`, + isRegression: baseConclusion ? conclusions.success.includes(baseConclusion) || conclusions.diagnostic.indexOf(headConclusion) < conclusions.diagnostic.indexOf(baseConclusion) ? true : false : null, + rank: 1 + } : null; + const diagnosticLevelOutcome = newDiagnostics.length > 0 ? { + severity: newDiagnostics[0].level, + description: `had at least one ${baseOutcome ? "new " : ""}${newDiagnostics[0].level} diagnostic`, + isRegression: baseOutcome ? true : null, + rank: 2 + } : null; + let checkFailureOutcome; + for (const { step, severity } of [ + { step: "build", severity: "error" }, + { step: "lint", severity: "warning" }, + { step: "test", severity: "warning" } + ]) { + if (checkFailures.includes(step)) { + checkFailureOutcome = { + severity, + description: `had a failure in the ${step} CI job`, + isRegression: baseChecks ? true : null, + rank: 3 + }; + break; } } - if (typeof tmp_sc.get(sentinel3) === "undefined") { - step = 0; - } + const worstOutcome = [ + categoryOutcome, + diagnosticLevelOutcome, + checkFailureOutcome + ].filter((r) => r !== null).sort( + (a, b) => ( + // sort by regression status then severity then rank + (!(a.severity === "fatal" || b.severity === "fatal") ? [true, null, false].indexOf(a.isRegression) - [true, null, false].indexOf(b.isRegression) : 0) || conclusions.diagnostic.indexOf(a.severity) - conclusions.diagnostic.indexOf(b.severity) || a.rank - b.rank + ) + )[0]; + return { + isPending: false, + conclusion: worstOutcome.severity, + ...worstOutcome + }; } - if (typeof filter === "function") { - obj = filter(prefix, obj); - } else if (obj instanceof Date) { - obj = serializeDate?.(obj); - } else if (generateArrayPrefix === "comma" && isArray3(obj)) { - obj = maybe_map3(obj, function(value) { - if (value instanceof Date) { - return serializeDate?.(value); - } - return value; - }); + if (conclusions.conflict.includes(headConclusion)) { + return { + isPending: false, + conclusion: "merge_conflict", + severity: baseConclusion !== "merge_conflict" ? "warning" : null, + description: "resulted in a merge conflict between your custom code and the newly generated changes", + isRegression: baseConclusion ? baseConclusion !== "merge_conflict" ? true : false : null + }; } - if (obj === null) { - if (strictNullHandling) { - return encoder && !encodeValuesOnly ? ( - // @ts-expect-error - encoder(prefix, defaults3.encoder, charset, "key", format) - ) : prefix; + return { + isPending: false, + conclusion: headConclusion, + severity: null, + description: headConclusion === "success" ? "was successful" : `had a conclusion of ${headConclusion}`, + isRegression: null + }; +} +function getReason({ + description, + isRegression +}) { + return `Your SDK build ${description}${isRegression === true ? ", which is a regression from the base state" : isRegression === false ? ", but this did not represent a regression" : ""}.`; +} +var DiagnosticLevel = ["fatal", "error", "warning", "note"]; +function countDiagnosticLevels(diagnostics) { + return diagnostics.reduce( + (counts, diag) => { + counts[diag.level] = (counts[diag.level] || 0) + 1; + return counts; + }, + { + fatal: 0, + error: 0, + warning: 0, + note: 0 } - obj = ""; + ); +} +function getNewDiagnostics(diagnostics, baseDiagnostics) { + if (!baseDiagnostics) { + return diagnostics; } - if (is_non_nullish_primitive3(obj) || is_buffer3(obj)) { - if (encoder) { - const key_value = encodeValuesOnly ? prefix : encoder(prefix, defaults3.encoder, charset, "key", format); - return [ - formatter?.(key_value) + "=" + // @ts-expect-error - formatter?.(encoder(obj, defaults3.encoder, charset, "value", format)) - ]; + return diagnostics.filter( + (d) => !baseDiagnostics.some( + (bd) => bd.code === d.code && bd.message === d.message && bd.config_ref === d.config_ref && bd.oas_ref === d.oas_ref + ) + ); +} +function sortDiagnostics(diagnostics) { + return diagnostics.sort( + (a, b) => DiagnosticLevel.indexOf(a.level) - DiagnosticLevel.indexOf(b.level) + ); +} +var CheckType = ["build", "lint", "test"]; +function getChecks(outcome) { + const results = {}; + const commitCompletedMoreThanXSecsAgo = outcome.commit ? (/* @__PURE__ */ new Date()).getTime() - new Date(outcome.commit.completed_at).getTime() > ASSUME_PENDING_CHECKS_SKIPPED_AFTER_SECS * 1e3 : false; + for (const checkType of CheckType) { + if (outcome[checkType]?.status === "not_started" && commitCompletedMoreThanXSecsAgo) { + outcome[checkType] = { + status: "completed", + conclusion: "skipped", + completed: { + conclusion: "skipped", + url: null + }, + url: null + }; } - return [formatter?.(prefix) + "=" + formatter?.(String(obj))]; - } - const values = []; - if (typeof obj === "undefined") { - return values; + results[checkType] = outcome[checkType] || null; } - let obj_keys; - if (generateArrayPrefix === "comma" && isArray3(obj)) { - if (encodeValuesOnly && encoder) { - obj = maybe_map3(obj, encoder); + return results; +} +function getNewChecks(headChecks, baseChecks) { + const result = {}; + for (const checkType of CheckType) { + const headCheck = headChecks[checkType]; + const baseCheck = baseChecks ? baseChecks[checkType] : null; + if (headCheck) { + const baseConclusion = baseCheck?.status === "completed" && baseCheck.conclusion; + const conclusion = headCheck.status === "completed" && headCheck.conclusion; + if (!baseConclusion || baseConclusion !== conclusion) { + result[checkType] = headCheck; + } } - obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; - } else if (isArray3(filter)) { - obj_keys = filter; - } else { - const keys = Object.keys(obj); - obj_keys = sort ? keys.sort(sort) : keys; - } - const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix); - const adjusted_prefix = commaRoundTrip && isArray3(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix; - if (allowEmptyArrays && isArray3(obj) && obj.length === 0) { - return adjusted_prefix + "[]"; } - for (let j = 0; j < obj_keys.length; ++j) { - const key = obj_keys[j]; - const value = ( - // @ts-ignore - typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key] - ); - if (skipNulls && value === null) { - continue; + return result; +} + +// src/comment.ts +var COMMENT_TITLE = Heading( + `${Symbol2.HeavyAsterisk} Stainless preview builds` +); +var COMMENT_FOOTER_DIVIDER = Comment("stainless-preview-footer"); +function printComment({ + noChanges, + orgName, + projectName, + branch, + commitMessage, + targetCommitMessages, + pendingAiCommitMessages, + baseOutcomes, + outcomes +}) { + const Blocks4 = (() => { + if (noChanges) { + return "No changes were made to the SDKs."; } - const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key; - const key_prefix = isArray3(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]"); - sideChannel.set(object, step); - const valueSideChannel = /* @__PURE__ */ new WeakMap(); - valueSideChannel.set(sentinel3, sideChannel); - push_to_array3(values, inner_stringify3( - value, - key_prefix, - generateArrayPrefix, - commaRoundTrip, - allowEmptyArrays, - strictNullHandling, - skipNulls, - encodeDotInKeys, - // @ts-ignore - generateArrayPrefix === "comma" && encodeValuesOnly && isArray3(obj) ? null : encoder, - filter, - sort, - allowDots, - serializeDate, - format, - formatter, - encodeValuesOnly, - charset, - valueSideChannel - )); - } - return values; + const canEdit = !!baseOutcomes; + return [ + Dedent` + This ${ctx().names.pr} will update the ${CodeInline( + projectName + )} SDKs with the following commit ${targetCommitMessages ? "messages" : "message"}. + `, + targetCommitMessages ? CommitMessagesSection({ + targets: Object.keys(outcomes).sort(), + pendingAiCommitMessages, + targetCommitMessages, + commitMessage + }) : CodeBlock(commitMessage), + !canEdit ? null : targetCommitMessages ? "Edit this comment to update them. They will appear in their respective SDK's changelogs." : "Edit this comment to update it. It will appear in the SDK's changelogs.", + Results({ orgName, projectName, branch, outcomes, baseOutcomes }) + ].filter((f) => f !== null).join(` + +`); + })(); + const dateString = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").replace(/\.\d+Z$/, " UTC"); + const fullComment = Dedent` + ${COMMENT_TITLE} + + ${Blocks4} + + ${Rule()} + + ${COMMENT_FOOTER_DIVIDER} + + ${Italic( + `This comment is auto-generated by ${ctx().names.ci} and is automatically kept up to date as you push.
If you push custom code to the preview branch, ${Link({ + text: `re-run this workflow`, + href: ctx().urls.run + })} to update the comment.
Last updated: ${dateString}` + )} + `; + return fullComment; } -function normalize_stringify_options3(opts = defaults3) { - if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") { - throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); - } - if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") { - throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided"); - } - if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") { - throw new TypeError("Encoder has to be a function."); - } - const charset = opts.charset || defaults3.charset; - if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { - throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); - } - let format = default_format3; - if (typeof opts.format !== "undefined") { - if (!has3(formatters3, opts.format)) { - throw new TypeError("Unknown format option provided."); +function CommitMessagesSection({ + targets, + pendingAiCommitMessages, + targetCommitMessages, + commitMessage +}) { + return targets.map((target) => { + const statusText = pendingAiCommitMessages?.has(target) ? `${Symbol2.HourglassFlowingSand} (generating...)` : ""; + const message = targetCommitMessages[target] ?? commitMessage; + return Dedent` + **${target}** + ${statusText}${CodeBlock(message)} + `; + }).join("\n"); +} +var DiagnosticIcon = { + fatal: Symbol2.Exclamation, + error: Symbol2.Exclamation, + warning: Symbol2.Warning, + note: Symbol2.Bulb +}; +function Results({ + orgName, + projectName, + branch, + outcomes, + baseOutcomes +}) { + const results = []; + let hasPending = false; + Object.entries(outcomes).forEach(([lang, head]) => { + const base = baseOutcomes?.[lang]; + hasPending ||= categorizeOutcome({ + outcome: head, + baseOutcome: base + }).isPending ?? false; + const result = Result({ + orgName, + projectName, + branch, + lang, + head, + base + }); + if (result) { + results.push(result); } - format = opts.format; - } - const formatter = formatters3[format]; - let filter = defaults3.filter; - if (typeof opts.filter === "function" || isArray3(opts.filter)) { - filter = opts.filter; - } - let arrayFormat; - if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators3) { - arrayFormat = opts.arrayFormat; - } else if ("indices" in opts) { - arrayFormat = opts.indices ? "indices" : "repeat"; - } else { - arrayFormat = defaults3.arrayFormat; - } - if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") { - throw new TypeError("`commaRoundTrip` must be a boolean, or absent"); + }); + if (hasPending) { + results.push( + Dedent` + ${Symbol2.HourglassFlowingSand} These are partial results; builds are still running. + ` + ); } - const allowDots = typeof opts.allowDots === "undefined" ? !!opts.encodeDotInKeys === true ? true : defaults3.allowDots : !!opts.allowDots; - return { - addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults3.addQueryPrefix, - // @ts-ignore - allowDots, - allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults3.allowEmptyArrays, - arrayFormat, - charset, - charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults3.charsetSentinel, - commaRoundTrip: !!opts.commaRoundTrip, - delimiter: typeof opts.delimiter === "undefined" ? defaults3.delimiter : opts.delimiter, - encode: typeof opts.encode === "boolean" ? opts.encode : defaults3.encode, - encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults3.encodeDotInKeys, - encoder: typeof opts.encoder === "function" ? opts.encoder : defaults3.encoder, - encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults3.encodeValuesOnly, - filter, - format, - formatter, - serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults3.serializeDate, - skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults3.skipNulls, - // @ts-ignore - sort: typeof opts.sort === "function" ? opts.sort : null, - strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults3.strictNullHandling - }; + return results.join("\n\n"); } -function stringify3(object, opts = {}) { - let obj = object; - const options = normalize_stringify_options3(opts); - let obj_keys; - let filter; - if (typeof options.filter === "function") { - filter = options.filter; - obj = filter("", obj); - } else if (isArray3(options.filter)) { - filter = options.filter; - obj_keys = filter; - } - const keys = []; - if (typeof obj !== "object" || obj === null) { - return ""; - } - const generateArrayPrefix = array_prefix_generators3[options.arrayFormat]; - const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip; - if (!obj_keys) { - obj_keys = Object.keys(obj); - } - if (options.sort) { - obj_keys.sort(options.sort); - } - const sideChannel = /* @__PURE__ */ new WeakMap(); - for (let i = 0; i < obj_keys.length; ++i) { - const key = obj_keys[i]; - if (options.skipNulls && obj[key] === null) { - continue; +function Result({ + orgName, + projectName, + branch, + lang, + head, + base +}) { + const categorized = categorizeOutcome({ + outcome: head, + baseOutcome: base + }); + const { ResultIcon, Description } = (() => { + if (categorized.isPending) { + return { + ResultIcon: Symbol2.HourglassFlowingSand, + Description: "" + }; } - push_to_array3(keys, inner_stringify3( - obj[key], - key, - // @ts-expect-error - generateArrayPrefix, - commaRoundTrip, - options.allowEmptyArrays, - options.strictNullHandling, - options.skipNulls, - options.encodeDotInKeys, - options.encode ? options.encoder : null, - options.filter, - options.sort, - options.allowDots, - options.serializeDate, - options.format, - options.formatter, - options.encodeValuesOnly, - options.charset, - sideChannel - )); - } - const joined = keys.join(options.delimiter); - let prefix = options.addQueryPrefix === true ? "?" : ""; - if (options.charsetSentinel) { - if (options.charset === "iso-8859-1") { - prefix += "utf8=%26%2310003%3B&"; - } else { - prefix += "utf8=%E2%9C%93&"; + const { severity, conclusion, isRegression, description } = categorized; + const reason = getReason({ + description, + isRegression + }); + if (isRegression !== false && severity === "fatal") { + return { + ResultIcon: Symbol2.Exclamation, + Description: Italic(reason) + }; } - } - return joined.length > 0 ? prefix + joined : ""; + if (isRegression !== false && conclusion === "merge_conflict") { + return { + ResultIcon: Symbol2.Zap, + Description: [ + Italic(reason), + Italic( + `You don't need to resolve this conflict right now, but you will need to resolve it for your changes to be released to your users. Read more about why this happened ${Link({ + text: "here", + href: "https://www.stainless.com/docs/guides/add-custom-code" + })}.` + ) + ].join("\n") + }; + } + if (isRegression !== false && severity !== "note" && severity !== null) { + return { + ResultIcon: Symbol2.Warning, + Description: Italic(reason) + }; + } + return { + ResultIcon: severity === "fatal" ? Symbol2.Construction : Symbol2.WhiteCheckMark, + Description: Italic(reason) + }; + })(); + return Details({ + summary: [ + ResultIcon, + Bold(`${projectName}-${lang}`), + [ + Link({ + text: "studio", + href: `https://app.stainless.com/${orgName}/${projectName}/studio?language=${lang}&branch=${encodeURIComponent(branch)}` + }), + GitHubLink(head), + base ? CompareLink(base, head) : null, + MergeConflictLink(head) + ].filter((link) => link !== null).join(` ${Symbol2.MiddleDot} `) + ].join(" "), + body: [ + Description, + StatusLine(base, head), + InstallationDetails(head, lang), + base ? DiagnosticsDetails(head, base) : null + ].filter((value) => Boolean(value)).join("\n"), + open: !categorized.isPending && categorized.isRegression !== false && categorized.severity !== "note" && categorized.severity !== null + }); } - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/query.mjs -function stringifyQuery(query) { - return stringify3(query, { arrayFormat: "comma" }); +function StatusLine(base, head) { + return [ + StatusStep(base, head, "generate"), + StatusStep(base, head, "build"), + StatusStep(base, head, "lint"), + StatusStep(base, head, "test") + ].filter((value) => Boolean(value)).join(` ${Symbol2.RightwardsArrow} `); } - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/log.mjs -var levelNumbers3 = { - off: 0, - error: 200, - warn: 300, - info: 400, - debug: 500 -}; -var parseLogLevel3 = (maybeLevel, sourceName, client) => { - if (!maybeLevel) { - return void 0; +function StatusStep(base, head, step) { + let baseStatus = base ? StatusSymbol(base, step) : null; + let headStatus = StatusSymbol(head, step); + if (!headStatus) { + return null; } - if (hasOwn3(levelNumbers3, maybeLevel)) { - return maybeLevel; + if (baseStatus === Symbol2.HourglassFlowingSand || headStatus === Symbol2.HourglassFlowingSand) { + baseStatus = Symbol2.HourglassFlowingSand; + headStatus = Symbol2.HourglassFlowingSand; } - loggerFor3(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers3))}`); - return void 0; -}; -function noop3() { + const headText = CodeInline(`${step} ${headStatus}`); + const headURL = StatusURL(head, step); + const headLink = headURL ? Link({ text: headText, href: headURL }) : headText; + if (!baseStatus || baseStatus === headStatus) { + return headLink; + } + const baseText = CodeInline(`${step} ${baseStatus}`); + const baseURL = StatusURL(base, step); + const baseLink = baseURL ? Link({ text: baseText, href: baseURL }) : baseText; + return `${headLink} (prev: ${baseLink})`; } -function makeLogFn3(fnLevel, logger2, logLevel) { - if (!logger2 || levelNumbers3[fnLevel] > levelNumbers3[logLevel]) { - return noop3; - } else { - return logger2[fnLevel].bind(logger2); +function StatusSymbol(outcome, step) { + if (!outcome.commit?.completed?.commit) { + return null; + } + if (step === "generate") { + switch (outcome.commit.completed.conclusion) { + case "fatal": + case "error": + case "cancelled": + return Symbol2.Exclamation; + case "merge_conflict": + return Symbol2.Zap; + case "upstream_merge_conflict": + case "warning": + return Symbol2.Warning; + default: + return Symbol2.WhiteCheckMark; + } + } + const stepData = outcome[step]; + if (!stepData) { + return null; + } + if (stepData.status === "completed") { + return stepData.completed.conclusion === "success" ? Symbol2.WhiteCheckMark : stepData.completed.conclusion === "skipped" ? Symbol2.Skipped : Symbol2.Exclamation; } + return Symbol2.HourglassFlowingSand; } -var noopLogger3 = { - error: noop3, - warn: noop3, - info: noop3, - debug: noop3 -}; -var cachedLoggers3 = /* @__PURE__ */ new WeakMap(); -function loggerFor3(client) { - const logger2 = client.logger; - const logLevel = client.logLevel ?? "off"; - if (!logger2) { - return noopLogger3; +function StatusURL(outcome, step) { + if (step === "generate" || !outcome[step]) { + return null; } - const cachedLogger = cachedLoggers3.get(logger2); - if (cachedLogger && cachedLogger[0] === logLevel) { - return cachedLogger[1]; + if (outcome[step].status !== "not_started") { + return outcome[step].url; } - const levelLogger = { - error: makeLogFn3("error", logger2, logLevel), - warn: makeLogFn3("warn", logger2, logLevel), - info: makeLogFn3("info", logger2, logLevel), - debug: makeLogFn3("debug", logger2, logLevel) - }; - cachedLoggers3.set(logger2, [logLevel, levelLogger]); - return levelLogger; } -var formatRequestDetails3 = (details) => { - if (details.options) { - details.options = { ...details.options }; - delete details.options["headers"]; +function GitHubLink(outcome) { + if (!outcome.commit?.completed?.commit) return null; + const { + repo: { owner, name, branch } + } = outcome.commit.completed.commit; + return Link({ + text: "code", + // This is a staging repo, so it's always GitHub. + href: `https://github.com/${owner}/${name}/tree/${encodeURIComponent(branch)}` + }); +} +function CompareLink(base, head) { + if (!base.commit?.completed?.commit || !head.commit?.completed?.commit) { + return null; } - if (details.headers) { - details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ - name, - name.toLowerCase() === "authorization" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value - ])); + const { repo } = head.commit.completed.commit; + const baseBranch = base.commit.completed.commit.repo.branch; + const headBranch = head.commit.completed.commit.repo.branch; + const compareURL = `https://github.com/${repo.owner}/${repo.name}/compare/${encodeURIComponent(baseBranch)}..${encodeURIComponent(headBranch)}`; + return Link({ text: "diff", href: compareURL }); +} +function MergeConflictLink(outcome) { + if (!outcome.commit?.completed?.merge_conflict_pr) return null; + const { + repo: { owner, name }, + number + } = outcome.commit.completed.merge_conflict_pr; + return Link({ + text: "conflict", + href: `https://github.com/${owner}/${name}/pull/${number}` + }); +} +function DiagnosticsDetails(head, base) { + if (!base.diagnostics || !head.diagnostics) return null; + const newDiagnostics = getNewDiagnostics(head.diagnostics, base.diagnostics); + if (newDiagnostics.length === 0) return null; + const levelCounts = countDiagnosticLevels(newDiagnostics); + const diagnosticCounts = Object.entries(levelCounts).filter(([, count]) => count > 0).map(([level, count]) => `${count} ${level}`); + const diagnosticList = sortDiagnostics(newDiagnostics).slice(0, 10).map((d) => `${DiagnosticIcon[d.level]} ${Bold(d.code)}: ${d.message}`).filter(Boolean); + const tableRows = diagnosticList.map((diagnostic) => ` +${diagnostic} +`).join("\n"); + const tableContent = ` +${tableRows} +
`; + return Details({ + summary: `New diagnostics (${diagnosticCounts.join(", ")})`, + body: tableContent, + indent: false + }); +} +function InstallationDetails(head, lang) { + let githubGoURL = null; + let installation = null; + if (head.commit?.completed.commit) { + const { repo, sha } = head.commit.completed.commit; + githubGoURL = `github.com/${repo.owner}/${repo.name}@${sha}`; } - if ("retryOfRequestLogID" in details) { - if (details.retryOfRequestLogID) { - details.retryOf = details.retryOfRequestLogID; + switch (lang) { + case "typescript": + case "node": { + if (head.install_url) { + installation = `npm install ${head.install_url}`; + } + break; } - delete details.retryOfRequestLogID; - } - return details; -}; - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/parse.mjs -async function defaultParseResponse3(client, props) { - const { response, requestLogID, retryOfRequestLogID, startTime } = props; - const body = await (async () => { - if (response.status === 204) { - return null; + case "python": { + if (head.install_url) { + installation = `pip install ${head.install_url}`; + } + break; } - if (props.options.__binaryResponse) { - return response; + case "go": { + if (githubGoURL) { + installation = `go get ${githubGoURL}`; + } + break; } - const contentType = response.headers.get("content-type"); - const mediaType = contentType?.split(";")[0]?.trim(); - const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json"); - if (isJSON) { - const contentLength = response.headers.get("content-length"); - if (contentLength === "0") { - return void 0; + case "java": { + if (head.install_url) { + installation = `Add the following URL as a Maven source: '${head.install_url}'`; } - const json = await response.json(); - return json; + break; + } + case "cli": { + if (head.install_url) { + installation = `Download and unzip: '${head.install_url}'. On macOS, run \`xattr -d com.apple.quarantine {executable name}\`.`; + } + break; + } + default: { + return null; } - const text = await response.text(); - return text; - })(); - loggerFor3(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails3({ - retryOfRequestLogID, - url: response.url, - status: response.status, - body, - durationMs: Date.now() - startTime - })); - return body; -} - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/core/api-promise.mjs -var _APIPromise_client3; -var APIPromise3 = class _APIPromise extends Promise { - constructor(client, responsePromise, parseResponse = defaultParseResponse3) { - super((resolve) => { - resolve(null); - }); - this.responsePromise = responsePromise; - this.parseResponse = parseResponse; - _APIPromise_client3.set(this, void 0); - __classPrivateFieldSet3(this, _APIPromise_client3, client, "f"); - } - _thenUnwrap(transform) { - return new _APIPromise(__classPrivateFieldGet3(this, _APIPromise_client3, "f"), this.responsePromise, async (client, props) => transform(await this.parseResponse(client, props), props)); - } - /** - * Gets the raw `Response` instance instead of parsing the response - * data. - * - * If you want to parse the response body but still get the `Response` - * instance, you can use {@link withResponse()}. - * - * 👋 Getting the wrong TypeScript type for `Response`? - * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` - * to your `tsconfig.json`. - */ - asResponse() { - return this.responsePromise.then((p) => p.response); } - /** - * Gets the parsed response data and the raw `Response` instance. - * - * If you just want to get the raw `Response` instance without parsing it, - * you can use {@link asResponse()}. - * - * 👋 Getting the wrong TypeScript type for `Response`? - * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` - * to your `tsconfig.json`. - */ - async withResponse() { - const [data, response] = await Promise.all([this.parse(), this.asResponse()]); - return { data, response }; + if (!installation) return null; + return CodeBlock({ content: installation, language: "bash" }); +} +function parseCommitMessages(body) { + if (!body) { + return {}; } - parse() { - if (!this.parsedPromise) { - this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet3(this, _APIPromise_client3, "f"), data)); + const targetCommitMessages = {}; + const languageBlocks = body.matchAll( + /\*\*([a-z_]+)\*\*\s*\n```\s*\n([\s\S]*?)\n```/g + ); + for (const match of languageBlocks) { + const language = match[1]; + const message2 = match[2].trim(); + if (message2) { + targetCommitMessages[language] = makeCommitMessageConventional(message2); } - return this.parsedPromise; } - then(onfulfilled, onrejected) { - return this.parse().then(onfulfilled, onrejected); + if (Object.keys(targetCommitMessages).length > 0) { + return { targetCommitMessages }; } - catch(onrejected) { - return this.parse().catch(onrejected); + const message = body?.match(/(? comment.body?.includes(COMMENT_TITLE) + ); + if (!existingComment) { + return null; } - finally(onfinally) { - return this.parse().finally(onfinally); + return { + id: existingComment.id, + ...parseCommitMessages(existingComment.body) + }; +} +async function upsertComment(prNumber, { + body, + skipCreate = false +}) { + logger.debug(`Upserting comment on ${ctx().names.pr} #${prNumber}`); + const comments = await api().listComments(prNumber); + const firstLine = body.trim().split("\n")[0]; + const existingComment = comments.find( + (comment) => comment.body?.includes(firstLine) + ); + if (existingComment) { + logger.debug("Updating existing comment:", existingComment.id); + await api().updateComment(prNumber, { ...existingComment, body }); + } else if (!skipCreate) { + logger.debug("Creating new comment"); + await api().createComment(prNumber, { body }); } +} +function areCommentsEqual(a, b) { + return a.slice(0, a.indexOf(COMMENT_FOOTER_DIVIDER)) === b.slice(0, b.indexOf(COMMENT_FOOTER_DIVIDER)); +} +function commentThrottler(prNumber) { + let lastComment = null; + let lastCommentTime = null; + return async ({ body, force = false }) => { + if (force || !lastComment || !lastCommentTime || !areCommentsEqual(body, lastComment) && Date.now() - lastCommentTime.getTime() > 10 * 1e3 || Date.now() - lastCommentTime.getTime() > 30 * 1e3) { + await upsertComment(prNumber, { body }); + lastComment = body; + lastCommentTime = /* @__PURE__ */ new Date(); + } + }; +} + +// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/context.js +var import_node_process = __toESM(require("node:process"), 1); +var import_node_util = require("node:util"); +var getContext = (raw) => ({ + start: import_node_process.default.hrtime.bigint(), + command: raw.map((part) => getCommandPart((0, import_node_util.stripVTControlCharacters)(part))).join(" "), + state: { stdout: "", stderr: "", output: "" } +}); +var getCommandPart = (part) => /[^\w./-]/.test(part) ? `'${part.replaceAll("'", "'\\''")}'` : part; + +// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/options.js +var import_node_path = __toESM(require("node:path"), 1); +var import_node_url = require("node:url"); +var import_node_process2 = __toESM(require("node:process"), 1); +var getOptions = ({ + stdin, + stdout, + stderr, + stdio = [stdin, stdout, stderr], + env: envOption, + preferLocal, + cwd: cwdOption = ".", + ...options +}) => { + const cwd = cwdOption instanceof URL ? (0, import_node_url.fileURLToPath)(cwdOption) : import_node_path.default.resolve(cwdOption); + const env = envOption ? { ...import_node_process2.default.env, ...envOption } : void 0; + const input = stdio[0]?.string; + return { + ...options, + input, + stdio: input === void 0 ? stdio : ["pipe", ...stdio.slice(1)], + env: preferLocal ? addLocalPath(env ?? import_node_process2.default.env, cwd) : env, + cwd + }; +}; +var addLocalPath = ({ Path: Path3 = "", PATH = Path3, ...env }, cwd) => { + const pathParts = PATH.split(import_node_path.default.delimiter); + const localPaths = getLocalPaths([], import_node_path.default.resolve(cwd)).map((localPath) => import_node_path.default.join(localPath, "node_modules/.bin")).filter((localPath) => !pathParts.includes(localPath)); + return { ...env, PATH: [...localPaths, PATH].filter(Boolean).join(import_node_path.default.delimiter) }; }; -_APIPromise_client3 = /* @__PURE__ */ new WeakMap(); +var getLocalPaths = (localPaths, localPath) => localPaths.at(-1) === localPath ? localPaths : getLocalPaths([...localPaths, localPath], import_node_path.default.resolve(localPath, "..")); -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/core/pagination.mjs -var _AbstractPage_client2; -var AbstractPage2 = class { - constructor(client, response, body, options) { - _AbstractPage_client2.set(this, void 0); - __classPrivateFieldSet3(this, _AbstractPage_client2, client, "f"); - this.options = options; - this.response = response; - this.body = body; - } - hasNextPage() { - const items = this.getPaginatedItems(); - if (!items.length) - return false; - return this.nextPageRequestOptions() != null; - } - async getNextPage() { - const nextOptions = this.nextPageRequestOptions(); - if (!nextOptions) { - throw new StainlessError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`."); - } - return await __classPrivateFieldGet3(this, _AbstractPage_client2, "f").requestAPIList(this.constructor, nextOptions); +// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/spawn.js +var import_node_child_process = require("node:child_process"); +var import_node_events2 = require("node:events"); +var import_node_process5 = __toESM(require("node:process"), 1); + +// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/windows.js +var import_promises = __toESM(require("node:fs/promises"), 1); +var import_node_path2 = __toESM(require("node:path"), 1); +var import_node_process3 = __toESM(require("node:process"), 1); +var applyForceShell = async (file, commandArguments, options) => await shouldForceShell(file, options) ? [escapeFile(file), commandArguments.map((argument) => escapeArgument(argument)), { ...options, shell: true }] : [file, commandArguments, options]; +var shouldForceShell = async (file, { shell, cwd, env = import_node_process3.default.env }) => import_node_process3.default.platform === "win32" && !shell && !await isExe(file, cwd, env); +var isExe = (file, cwd, { Path: Path3 = "", PATH = Path3 }) => ( + // If the *.exe or *.com file extension was not omitted. + // Windows common file systems are case-insensitive. + exeExtensions.some((extension) => file.toLowerCase().endsWith(extension)) || mIsExe(file, cwd, PATH) +); +var EXE_MEMO = {}; +var memoize = (function_) => (...arguments_) => ( + // Use returned assignment to keep code small + EXE_MEMO[arguments_.join("\0")] ??= function_(...arguments_) +); +var access = memoize(import_promises.default.access); +var mIsExe = memoize(async (file, cwd, PATH) => { + const parts = PATH.split(import_node_path2.default.delimiter).filter(Boolean).map((part) => part.replace(/^"(.*)"$/, "$1")); + try { + await Promise.any( + [cwd, ...parts].flatMap( + (part) => exeExtensions.map((extension) => access(`${import_node_path2.default.resolve(part, file)}${extension}`)) + ) + ); + } catch { + return false; } - async *iterPages() { - let page = this; - yield page; - while (page.hasNextPage()) { - page = await page.getNextPage(); - yield page; - } + return true; +}); +var exeExtensions = [".exe", ".com"]; +var escapeArgument = (argument) => escapeFile(escapeFile(`"${argument.replaceAll(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, "$1$1")}"`)); +var escapeFile = (file) => file.replaceAll(/([()\][%!^"`<>&|;, *?])/g, "^$1"); + +// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/result.js +var import_node_events = require("node:events"); +var import_node_process4 = __toESM(require("node:process"), 1); +var getResult = async (nodeChildProcess, { input }, context) => { + const instance = await nodeChildProcess; + if (input !== void 0) { + instance.stdin.end(input); } - async *[(_AbstractPage_client2 = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() { - for await (const page of this.iterPages()) { - for (const item of page.getPaginatedItems()) { - yield item; - } - } + const onClose = (0, import_node_events.once)(instance, "close"); + try { + await Promise.race([ + onClose, + ...instance.stdio.filter(Boolean).map((stream) => onStreamError(stream)) + ]); + checkFailure(context, getErrorOutput(instance)); + return getOutputs(context); + } catch (error) { + await Promise.allSettled([onClose]); + throw getResultError(error, instance, context); } }; -var PagePromise2 = class extends APIPromise3 { - constructor(client, request, Page2) { - super(client, request, async (client2, props) => new Page2(client2, props.response, await defaultParseResponse3(client2, props), props.options)); - } - /** - * Allow auto-paginating iteration on an unawaited list call, eg: - * - * for await (const item of client.items.list()) { - * console.log(item) - * } - */ - async *[Symbol.asyncIterator]() { - const page = await this; - for await (const item of page) { - yield item; +var onStreamError = async (stream) => { + for await (const [error] of (0, import_node_events.on)(stream, "error")) { + if (!["ERR_STREAM_PREMATURE_CLOSE", "EPIPE"].includes(error?.code)) { + throw error; } } }; -var Page = class extends AbstractPage2 { - constructor(client, response, body, options) { - super(client, response, body, options); - this.data = body.data || []; - this.next_cursor = body.next_cursor || ""; - } - getPaginatedItems() { - return this.data ?? []; +var checkFailure = ({ command }, { exitCode, signalName }) => { + if (signalName !== void 0) { + throw new SubprocessError(`Command was terminated with ${signalName}: ${command}`); } - nextPageRequestOptions() { - const cursor = this.next_cursor; - if (!cursor) { - return null; - } - return { - ...this.options, - query: { - ...maybeObj2(this.options.query), - cursor - } - }; + if (exitCode !== void 0) { + throw new SubprocessError(`Command failed with exit code ${exitCode}: ${command}`); } }; - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/uploads.mjs -var checkFileSupport3 = () => { - if (typeof File === "undefined") { - const { process: process7 } = globalThis; - const isOldNode = typeof process7?.versions?.node === "string" && parseInt(process7.versions.node.split(".")) < 20; - throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : "")); - } +var getResultError = (error, instance, context) => Object.assign( + getErrorInstance(error, context), + getErrorOutput(instance), + getOutputs(context) +); +var getErrorInstance = (error, { command }) => error instanceof SubprocessError ? error : new SubprocessError(`Command failed: ${command}`, { cause: error }); +var SubprocessError = class extends Error { + name = "SubprocessError"; }; -function makeFile3(fileBits, fileName, options) { - checkFileSupport3(); - return new File(fileBits, fileName ?? "unknown_file", options); -} -function getName3(value) { - return (typeof value === "object" && value !== null && ("name" in value && value.name && String(value.name) || "url" in value && value.url && String(value.url) || "filename" in value && value.filename && String(value.filename) || "path" in value && value.path && String(value.path)) || "").split(/[\\/]/).pop() || void 0; -} -var isAsyncIterable3 = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function"; +var getErrorOutput = ({ exitCode, signalCode }) => ({ + // `exitCode` can be a negative number (`errno`) when the `error` event is emitted on the `instance` + ...exitCode < 1 ? {} : { exitCode }, + ...signalCode === null ? {} : { signalName: signalCode } +}); +var getOutputs = ({ state: { stdout, stderr, output }, command, start }) => ({ + stdout: getOutput(stdout), + stderr: getOutput(stderr), + output: getOutput(output), + command, + durationMs: Number(import_node_process4.default.hrtime.bigint() - start) / 1e6 +}); +var getOutput = (output) => output.at(-1) === "\n" ? output.slice(0, output.at(-2) === "\r" ? -2 : -1) : output; -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/to-file.mjs -var isBlobLike = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function"; -var isFileLike = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value); -var isResponseLike = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function"; -async function toFile3(value, name, options) { - checkFileSupport3(); - value = await value; - if (isFileLike(value)) { - if (value instanceof File) { - return value; - } - return makeFile3([await value.arrayBuffer()], value.name); - } - if (isResponseLike(value)) { - const blob = await value.blob(); - name || (name = new URL(value.url).pathname.split(/[\\/]/).pop()); - return makeFile3(await getBytes(blob), name, options); - } - const parts = await getBytes(value); - name || (name = getName3(value)); - if (!options?.type) { - const type = parts.find((part) => typeof part === "object" && "type" in part && part.type); - if (typeof type === "string") { - options = { ...options, type }; +// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/spawn.js +var spawnSubprocess = async (file, commandArguments, options, context) => { + try { + if (["node", "node.exe"].includes(file.toLowerCase())) { + file = import_node_process5.default.execPath; + commandArguments = [...import_node_process5.default.execArgv.filter((flag) => !flag.startsWith("--inspect")), ...commandArguments]; } + [file, commandArguments, options] = await applyForceShell(file, commandArguments, options); + [file, commandArguments, options] = concatenateShell(file, commandArguments, options); + const instance = (0, import_node_child_process.spawn)(file, commandArguments, options); + bufferOutput(instance.stdout, context, "stdout"); + bufferOutput(instance.stderr, context, "stderr"); + instance.once("error", () => { + }); + await (0, import_node_events2.once)(instance, "spawn"); + return instance; + } catch (error) { + throw getResultError(error, {}, context); } - return makeFile3(parts, name, options); -} -async function getBytes(value) { - let parts = []; - if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. - value instanceof ArrayBuffer) { - parts.push(value); - } else if (isBlobLike(value)) { - parts.push(value instanceof Blob ? value : await value.arrayBuffer()); - } else if (isAsyncIterable3(value)) { - for await (const chunk of value) { - parts.push(...await getBytes(chunk)); +}; +var concatenateShell = (file, commandArguments, options) => options.shell && commandArguments.length > 0 ? [[file, ...commandArguments].join(" "), [], options] : [file, commandArguments, options]; +var bufferOutput = (stream, { state }, streamName) => { + if (stream) { + stream.setEncoding("utf8"); + if (!state.isIterating) { + state.isIterating = false; + stream.on("data", (chunk) => { + state[streamName] += chunk; + state.output += chunk; + }); } - } else { - const constructor = value?.constructor?.name; - throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError(value)}`); } - return parts; -} -function propsForError(value) { - if (typeof value !== "object" || value === null) - return ""; - const props = Object.getOwnPropertyNames(value); - return `; props: [${props.map((p) => `"${p}"`).join(", ")}]`; -} +}; -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/core/resource.mjs -var APIResource3 = class { - constructor(client) { - this._client = client; +// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/pipe.js +var import_promises2 = require("node:stream/promises"); +var handlePipe = async (subprocesses) => { + const [[from, to]] = await Promise.all([Promise.allSettled(subprocesses), pipeStreams(subprocesses)]); + if (to.reason) { + to.reason.pipedFrom = from.reason ?? from.value; + throw to.reason; + } + if (from.reason) { + throw from.reason; } + return { ...to.value, pipedFrom: from.value }; }; - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/path.mjs -function encodeURIPath3(str) { - return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); -} -var EMPTY3 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); -var createPathTagFunction3 = (pathEncoder = encodeURIPath3) => function path7(statics, ...params) { - if (statics.length === 1) - return statics[0]; - let postPath = false; - const invalidSegments = []; - const path8 = statics.reduce((previousValue, currentValue, index) => { - if (/[?#]/.test(currentValue)) { - postPath = true; +var pipeStreams = async (subprocesses) => { + try { + const [{ stdout }, { stdin }] = await Promise.all(subprocesses.map(({ nodeChildProcess }) => nodeChildProcess)); + if (stdin === null) { + throw new Error('The "stdin" option must be set on the first "spawn()" call in the pipeline.'); } - const value = params[index]; - let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value); - if (index !== params.length && (value == null || typeof value === "object" && // handle values from other realms - value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY3) ?? EMPTY3)?.toString)) { - encoded = value + ""; - invalidSegments.push({ - start: previousValue.length + currentValue.length, - length: encoded.length, - error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter` - }); + if (stdout === null) { + throw new Error('The "stdout" option must be set on the last "spawn()" call in the pipeline.'); } - return previousValue + currentValue + (index === params.length ? "" : encoded); - }, ""); - const pathOnly = path8.split(/[?#]/, 1)[0]; - const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; - let match; - while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) { - invalidSegments.push({ - start: match.index, - length: match[0].length, - error: `Value "${match[0]}" can't be safely passed as a path parameter` + (0, import_promises2.pipeline)(stdout, stdin).catch(() => { }); + } catch (error) { + await Promise.allSettled(subprocesses.map(({ nodeChildProcess }) => closeStdin(nodeChildProcess))); + throw error; } - invalidSegments.sort((a, b) => a.start - b.start); - if (invalidSegments.length > 0) { - let lastEnd = 0; - const underline = invalidSegments.reduce((acc, segment) => { - const spaces = " ".repeat(segment.start - lastEnd); - const arrows = "^".repeat(segment.length); - lastEnd = segment.start + segment.length; - return acc + spaces + arrows; - }, ""); - throw new StainlessError(`Path parameters result in path with invalid segments: -${invalidSegments.map((e) => e.error).join("\n")} -${path8} -${underline}`); - } - return path8; }; -var path6 = /* @__PURE__ */ createPathTagFunction3(encodeURIPath3); +var closeStdin = async (nodeChildProcess) => { + const { stdin } = await nodeChildProcess; + stdin.end(); +}; -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/builds/diagnostics.mjs -var Diagnostics = class extends APIResource3 { - /** - * Get the list of diagnostics for a given build. - * - * If no language targets are specified, diagnostics for all languages are - * returned. - */ - list(buildID, query = {}, options) { - return this._client.getAPIList(path6`/v0/builds/${buildID}/diagnostics`, Page, { - query, - ...options - }); +// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/iterable.js +var readline = __toESM(require("node:readline/promises"), 1); +var lineIterator = async function* (subprocess, { state }, streamName) { + if (state.isIterating === false) { + throw new Error(`The subprocess must be iterated right away, for example: + for await (const line of spawn(...)) { ... }`); + } + state.isIterating = true; + try { + const { [streamName]: stream } = await subprocess.nodeChildProcess; + if (!stream) { + return; + } + handleErrors(subprocess); + yield* readline.createInterface({ input: stream }); + } finally { + await subprocess; } }; - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/builds/target-outputs.mjs -var TargetOutputs = class extends APIResource3 { - /** - * Retrieve a method to download an output for a given build target. - * - * If the requested type of output is `source`, and the requested output method is - * `url`, a download link to a tarball of the source files is returned. If the - * requested output method is `git`, a Git remote, ref, and access token (if - * necessary) is returned. - * - * Otherwise, the possible types of outputs are specific to the requested target, - * and the output method _must_ be `url`. See the documentation for `type` for more - * information. - */ - retrieve(query, options) { - return this._client.get("/v0/build_target_outputs", { query, ...options }); +var handleErrors = async (subprocess) => { + try { + await subprocess; + } catch { + } +}; +var combineAsyncIterators = async function* (...iterators) { + try { + let promises = []; + while (iterators.length > 0) { + promises = iterators.map((iterator2, index2) => promises[index2] ?? getNext(iterator2)); + const [{ value, done }, index] = await Promise.race(promises.map((promise, index2) => Promise.all([promise, index2]))); + const [iterator] = iterators.splice(index, 1); + promises.splice(index, 1); + if (!done) { + iterators.push(iterator); + yield value; + } + } + } finally { + await Promise.all(iterators.map((iterator) => iterator.return())); + } +}; +var getNext = async (iterator) => { + try { + return await iterator.next(); + } catch (error) { + await iterator.throw(error); } }; -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/builds/builds.mjs -var Builds2 = class extends APIResource3 { - constructor() { - super(...arguments); - this.diagnostics = new Diagnostics(this._client); - this.targetOutputs = new TargetOutputs(this._client); +// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/index.js +function spawn2(file, second, third, previous) { + const [commandArguments = [], options = {}] = Array.isArray(second) ? [second, third] : [[], second]; + const context = getContext([file, ...commandArguments]); + const spawnOptions = getOptions(options); + const nodeChildProcess = spawnSubprocess(file, commandArguments, spawnOptions, context); + let subprocess = getResult(nodeChildProcess, spawnOptions, context); + Object.assign(subprocess, { nodeChildProcess }); + subprocess = previous ? handlePipe([previous, subprocess]) : subprocess; + const stdout = lineIterator(subprocess, context, "stdout"); + const stderr = lineIterator(subprocess, context, "stderr"); + return Object.assign(subprocess, { + nodeChildProcess, + stdout, + stderr, + [Symbol.asyncIterator]: () => combineAsyncIterators(stdout, stderr), + pipe: (file2, second2, third2) => spawn2(file2, second2, third2, subprocess) + }); +} + +// src/config.ts +var fs4 = __toESM(require("node:fs")); +var import_node_os = require("node:os"); +var path6 = __toESM(require("node:path")); +function getSavedFilePath(file, sha, extension) { + return path6.join( + (0, import_node_os.tmpdir)(), + "stainless-generated-config", + `${file}-${sha}${extension}` + ); +} +async function saveConfig({ + oasPath, + configPath +}) { + let hasOAS = false; + let hasConfig = false; + const savedSha = (await spawn2("git", ["rev-parse", "HEAD"])).stdout.trim(); + if (!savedSha) { + throw new Error("Unable to determine current SHA; is there a git repo?"); + } + logger.info("Saving generated config for", savedSha); + if (oasPath && fs4.existsSync(oasPath)) { + hasOAS = true; + const savedFilePath = getSavedFilePath( + "oas", + savedSha, + path6.extname(oasPath) + ); + fs4.mkdirSync(path6.dirname(savedFilePath), { recursive: true }); + fs4.copyFileSync(oasPath, savedFilePath); + fs4.rmSync(oasPath); + logger.info(`Saved OAS file to ${savedFilePath}`); + } + if (configPath && fs4.existsSync(configPath)) { + hasConfig = true; + const savedFilePath = getSavedFilePath( + "config", + savedSha, + path6.extname(configPath) + ); + fs4.mkdirSync(path6.dirname(savedFilePath), { recursive: true }); + fs4.copyFileSync(configPath, savedFilePath); + fs4.rmSync(configPath); + logger.info(`Saved config file to ${savedFilePath}`); + } + return { hasOAS, hasConfig, savedSha }; +} +async function readConfig({ + oasPath, + configPath, + sha, + required = false +}) { + sha ??= (await spawn2("git", ["rev-parse", "HEAD"])).stdout; + if (!sha) { + throw new Error("Unable to determine current SHA; is there a git repo?"); + } + logger.info("Reading config at SHA", sha); + const results = {}; + const addToResults = async (file, filePath, via) => { + if (results[file]) { + return; + } + if (!filePath || !fs4.existsSync(filePath)) { + logger.debug(`Skipping missing ${file} at ${filePath}`); + return; + } + results[file] = fs4.readFileSync(filePath, "utf-8"); + results[`${file}Hash`] = (await spawn2("md5sum", [filePath])).stdout.split( + " " + )[0]; + logger.info(`Using ${file} via ${via}`, { hash: results[`${file}Hash`] }); + }; + try { + await spawn2("git", ["fetch", "--depth=1", "origin", sha]).catch(() => null); + await spawn2("git", ["checkout", sha, "--", "."]); + } catch { + logger.debug("Could not checkout", sha); } - /** - * Create a build, on top of a project branch, against a given input revision. - * - * The project branch will be modified so that its latest set of config files - * points to the one specified by the input revision. - */ - create(params, options) { - const { project = this._client.project, ...body } = params; - return this._client.post("/v0/builds", { body: { project, ...body }, ...options }); + await addToResults("oas", oasPath, `git ${sha}`); + await addToResults("config", configPath, `git ${sha}`); + try { + await addToResults( + "oas", + getSavedFilePath("oas", sha, path6.extname(oasPath ?? "")), + `saved ${sha}` + ); + await addToResults( + "config", + getSavedFilePath("config", sha, path6.extname(configPath ?? "")), + `saved ${sha}` + ); + } catch (e) { + logger.info(`Could not get config from saved file path: ${e}`); + logger.debug("Could not get config from saved file path"); } - /** - * Retrieve a build by its ID. - */ - retrieve(buildID, options) { - return this._client.get(path6`/v0/builds/${buildID}`, options); + if (required) { + if (oasPath && !results.oas) { + throw new Error(`Missing OpenAPI spec at ${oasPath} for ${sha}`); + } + if (configPath && !results.config) { + throw new Error(`Missing config at ${configPath} for ${sha}`); + } } - /** - * List user-triggered builds for a given project. - * - * An optional revision can be specified to filter by config commit SHA, or hashes - * of file contents. - */ - list(params = {}, options) { - const { project = this._client.project, ...query } = params ?? {}; - return this._client.getAPIList("/v0/builds", Page, { query: { project, ...query }, ...options }); + return results; +} +async function isConfigChanged({ + before, + after +}) { + let changed = false; + if (before.oasHash !== after.oasHash) { + logger.debug("OAS file changed"); + changed = true; } - /** - * Create two builds whose outputs can be directly compared with each other. - * - * Created builds _modify_ their project branches so that their latest sets of - * config files point to the ones specified by the input revision. - * - * This endpoint is useful because a build has more inputs than the set of config - * files it uses, so comparing two builds directly may return spurious differences. - * Builds made via this endpoint are guaranteed to have differences arising from - * the set of config files, and any custom code. - */ - compare(params, options) { - const { project = this._client.project, ...body } = params; - return this._client.post("/v0/builds/compare", { body: { project, ...body }, ...options }); + if (before.configHash !== after.configHash) { + logger.debug("Config file changed"); + changed = true; } -}; -Builds2.Diagnostics = Diagnostics; -Builds2.TargetOutputs = TargetOutputs; + return changed; +} -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/orgs.mjs -var Orgs3 = class extends APIResource3 { - /** - * Retrieve an organization by name. - */ - retrieve(org, options) { - return this._client.get(path6`/v0/orgs/${org}`, options); +// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/diff/base.js +var Diff = class { + diff(oldStr, newStr, options = {}) { + let callback; + if (typeof options === "function") { + callback = options; + options = {}; + } else if ("callback" in options) { + callback = options.callback; + } + const oldString = this.castInput(oldStr, options); + const newString = this.castInput(newStr, options); + const oldTokens = this.removeEmpty(this.tokenize(oldString, options)); + const newTokens = this.removeEmpty(this.tokenize(newString, options)); + return this.diffWithOptionsObj(oldTokens, newTokens, options, callback); } - /** - * List organizations accessible to the current authentication method. - */ - list(options) { - return this._client.get("/v0/orgs", options); + diffWithOptionsObj(oldTokens, newTokens, options, callback) { + var _a2; + const done = (value) => { + value = this.postProcess(value, options); + if (callback) { + setTimeout(function() { + callback(value); + }, 0); + return void 0; + } else { + return value; + } + }; + const newLen = newTokens.length, oldLen = oldTokens.length; + let editLength = 1; + let maxEditLength = newLen + oldLen; + if (options.maxEditLength != null) { + maxEditLength = Math.min(maxEditLength, options.maxEditLength); + } + const maxExecutionTime = (_a2 = options.timeout) !== null && _a2 !== void 0 ? _a2 : Infinity; + const abortAfterTimestamp = Date.now() + maxExecutionTime; + const bestPath = [{ oldPos: -1, lastComponent: void 0 }]; + let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options); + if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) { + return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens)); + } + let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity; + const execEditLength = () => { + for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) { + let basePath; + const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1]; + if (removePath) { + bestPath[diagonalPath - 1] = void 0; + } + let canAdd = false; + if (addPath) { + const addPathNewPos = addPath.oldPos - diagonalPath; + canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen; + } + const canRemove = removePath && removePath.oldPos + 1 < oldLen; + if (!canAdd && !canRemove) { + bestPath[diagonalPath] = void 0; + continue; + } + if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) { + basePath = this.addToPath(addPath, true, false, 0, options); + } else { + basePath = this.addToPath(removePath, false, true, 1, options); + } + newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options); + if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) { + return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true; + } else { + bestPath[diagonalPath] = basePath; + if (basePath.oldPos + 1 >= oldLen) { + maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1); + } + if (newPos + 1 >= newLen) { + minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1); + } + } + } + editLength++; + }; + if (callback) { + (function exec() { + setTimeout(function() { + if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) { + return callback(void 0); + } + if (!execEditLength()) { + exec(); + } + }, 0); + })(); + } else { + while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) { + const ret = execEditLength(); + if (ret) { + return ret; + } + } + } } -}; - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/projects/branches.mjs -var Branches3 = class extends APIResource3 { - /** - * Create a new branch for a project. - * - * The branch inherits the config files from the revision pointed to by the - * `branch_from` parameter. In addition, if the revision is a branch name, the - * branch will also inherit custom code changes from that branch. - */ - create(params, options) { - const { project = this._client.project, ...body } = params; - return this._client.post(path6`/v0/projects/${project}/branches`, { body, ...options }); + addToPath(path7, added, removed, oldPosInc, options) { + const last = path7.lastComponent; + if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) { + return { + oldPos: path7.oldPos + oldPosInc, + lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent } + }; + } else { + return { + oldPos: path7.oldPos + oldPosInc, + lastComponent: { count: 1, added, removed, previousComponent: last } + }; + } } - /** - * Retrieve a project branch by name. - */ - retrieve(branch, params = {}, options) { - const { project = this._client.project } = params ?? {}; - return this._client.get(path6`/v0/projects/${project}/branches/${branch}`, options); + extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) { + const newLen = newTokens.length, oldLen = oldTokens.length; + let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0; + while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) { + newPos++; + oldPos++; + commonCount++; + if (options.oneChangePerToken) { + basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false }; + } + } + if (commonCount && !options.oneChangePerToken) { + basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false }; + } + basePath.oldPos = oldPos; + return newPos; } - /** - * Retrieve a project branch by name. - */ - list(params = {}, options) { - const { project = this._client.project, ...query } = params ?? {}; - return this._client.getAPIList(path6`/v0/projects/${project}/branches`, Page, { - query, - ...options - }); + equals(left, right, options) { + if (options.comparator) { + return options.comparator(left, right); + } else { + return left === right || !!options.ignoreCase && left.toLowerCase() === right.toLowerCase(); + } + } + removeEmpty(array) { + const ret = []; + for (let i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]); + } + } + return ret; } - /** - * Delete a project branch by name. - */ - delete(branch, params = {}, options) { - const { project = this._client.project } = params ?? {}; - return this._client.delete(path6`/v0/projects/${project}/branches/${branch}`, options); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + castInput(value, options) { + return value; } - /** - * Rebase a project branch. - * - * The branch is rebased onto the `base` branch or commit SHA, inheriting any - * config and custom code changes. - */ - rebase(branch, params = {}, options) { - const { project = this._client.project, base } = params ?? {}; - return this._client.put(path6`/v0/projects/${project}/branches/${branch}/rebase`, { - query: { base }, - ...options - }); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + tokenize(value, options) { + return Array.from(value); } - /** - * Reset a project branch. - * - * If `branch` === `main`, the branch is reset to `target_config_sha`. Otherwise, - * the branch is reset to `main`. - */ - reset(branch, params = {}, options) { - const { project = this._client.project, target_config_sha } = params ?? {}; - return this._client.put(path6`/v0/projects/${project}/branches/${branch}/reset`, { - query: { target_config_sha }, - ...options - }); + join(chars) { + return chars.join(""); } -}; - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/projects/configs.mjs -var Configs = class extends APIResource3 { - /** - * Retrieve the configuration files for a given project. - */ - retrieve(params = {}, options) { - const { project = this._client.project, ...query } = params ?? {}; - return this._client.get(path6`/v0/projects/${project}/configs`, { query, ...options }); + postProcess(changeObjects, options) { + return changeObjects; } - /** - * Generate suggestions for changes to config files based on an OpenAPI spec. - */ - guess(params, options) { - const { project = this._client.project, ...body } = params; - return this._client.post(path6`/v0/projects/${project}/configs/guess`, { body, ...options }); + get useLongestToken() { + return false; + } + buildValues(lastComponent, newTokens, oldTokens) { + const components = []; + let nextComponent; + while (lastComponent) { + components.push(lastComponent); + nextComponent = lastComponent.previousComponent; + delete lastComponent.previousComponent; + lastComponent = nextComponent; + } + components.reverse(); + const componentLen = components.length; + let componentPos = 0, newPos = 0, oldPos = 0; + for (; componentPos < componentLen; componentPos++) { + const component = components[componentPos]; + if (!component.removed) { + if (!component.added && this.useLongestToken) { + let value = newTokens.slice(newPos, newPos + component.count); + value = value.map(function(value2, i) { + const oldValue = oldTokens[oldPos + i]; + return oldValue.length > value2.length ? oldValue : value2; + }); + component.value = this.join(value); + } else { + component.value = this.join(newTokens.slice(newPos, newPos + component.count)); + } + newPos += component.count; + if (!component.added) { + oldPos += component.count; + } + } else { + component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count)); + oldPos += component.count; + } + } + return components; } }; -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/projects/projects.mjs -var Projects5 = class extends APIResource3 { +// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/util/string.js +function hasOnlyWinLineEndings(string) { + return string.includes("\r\n") && !string.startsWith("\n") && !string.match(/[^\r]\n/); +} +function hasOnlyUnixLineEndings(string) { + return !string.includes("\r\n") && string.includes("\n"); +} + +// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/diff/line.js +var LineDiff = class extends Diff { constructor() { super(...arguments); - this.branches = new Branches3(this._client); - this.configs = new Configs(this._client); - } - /** - * Create a new project. - */ - create(body, options) { - return this._client.post("/v0/projects", { body, ...options }); + this.tokenize = tokenize; } - /** - * Retrieve a project by name. - */ - retrieve(params = {}, options) { - const { project = this._client.project } = params ?? {}; - return this._client.get(path6`/v0/projects/${project}`, options); + equals(left, right, options) { + if (options.ignoreWhitespace) { + if (!options.newlineIsToken || !left.includes("\n")) { + left = left.trim(); + } + if (!options.newlineIsToken || !right.includes("\n")) { + right = right.trim(); + } + } else if (options.ignoreNewlineAtEof && !options.newlineIsToken) { + if (left.endsWith("\n")) { + left = left.slice(0, -1); + } + if (right.endsWith("\n")) { + right = right.slice(0, -1); + } + } + return super.equals(left, right, options); } - /** - * Update a project's properties. - */ - update(params = {}, options) { - const { project = this._client.project, ...body } = params ?? {}; - return this._client.patch(path6`/v0/projects/${project}`, { body, ...options }); +}; +var lineDiff = new LineDiff(); +function diffLines(oldStr, newStr, options) { + return lineDiff.diff(oldStr, newStr, options); +} +function tokenize(value, options) { + if (options.stripTrailingCr) { + value = value.replace(/\r\n/g, "\n"); } - /** - * List projects in an organization, from oldest to newest. - */ - list(query = {}, options) { - return this._client.getAPIList("/v0/projects", Page, { query, ...options }); + const retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/); + if (!linesAndNewlines[linesAndNewlines.length - 1]) { + linesAndNewlines.pop(); } - /** - * Generates an AI commit message by comparing two git refs in the SDK repository. - */ - generateCommitMessage(params, options) { - const { project = this._client.project, target, ...body } = params; - return this._client.post(path6`/v0/projects/${project}/generate_commit_message`, { - query: { target }, - body, - ...options - }); + for (let i = 0; i < linesAndNewlines.length; i++) { + const line = linesAndNewlines[i]; + if (i % 2 && !options.newlineIsToken) { + retLines[retLines.length - 1] += line; + } else { + retLines.push(line); + } } -}; -Projects5.Branches = Branches3; -Projects5.Configs = Configs; + return retLines; +} -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/user.mjs -var User = class extends APIResource3 { - /** - * Retrieve the currently authenticated user's information. - */ - retrieve(options) { - return this._client.get("/v0/user", options); +// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/line-endings.js +function unixToWin(patch) { + if (Array.isArray(patch)) { + return patch.map((p) => unixToWin(p)); } -}; - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/headers.mjs -var brand_privateNullableHeaders3 = /* @__PURE__ */ Symbol("brand.privateNullableHeaders"); -function* iterateHeaders3(headers) { - if (!headers) - return; - if (brand_privateNullableHeaders3 in headers) { - const { values, nulls } = headers; - yield* values.entries(); - for (const name of nulls) { - yield [name, null]; - } - return; + return Object.assign(Object.assign({}, patch), { hunks: patch.hunks.map((hunk) => Object.assign(Object.assign({}, hunk), { lines: hunk.lines.map((line, i) => { + var _a2; + return line.startsWith("\\") || line.endsWith("\r") || ((_a2 = hunk.lines[i + 1]) === null || _a2 === void 0 ? void 0 : _a2.startsWith("\\")) ? line : line + "\r"; + }) })) }); +} +function winToUnix(patch) { + if (Array.isArray(patch)) { + return patch.map((p) => winToUnix(p)); } - let shouldClear = false; - let iter; - if (headers instanceof Headers) { - iter = headers.entries(); - } else if (isReadonlyArray3(headers)) { - iter = headers; - } else { - shouldClear = true; - iter = Object.entries(headers ?? {}); + return Object.assign(Object.assign({}, patch), { hunks: patch.hunks.map((hunk) => Object.assign(Object.assign({}, hunk), { lines: hunk.lines.map((line) => line.endsWith("\r") ? line.substring(0, line.length - 1) : line) })) }); +} +function isUnix(patch) { + if (!Array.isArray(patch)) { + patch = [patch]; } - for (let row of iter) { - const name = row[0]; - if (typeof name !== "string") - throw new TypeError("expected header name to be a string"); - const values = isReadonlyArray3(row[1]) ? row[1] : [row[1]]; - let didClear = false; - for (const value of values) { - if (value === void 0) - continue; - if (shouldClear && !didClear) { - didClear = true; - yield [name, null]; + return !patch.some((index) => index.hunks.some((hunk) => hunk.lines.some((line) => !line.startsWith("\\") && line.endsWith("\r")))); +} +function isWin(patch) { + if (!Array.isArray(patch)) { + patch = [patch]; + } + return patch.some((index) => index.hunks.some((hunk) => hunk.lines.some((line) => line.endsWith("\r")))) && patch.every((index) => index.hunks.every((hunk) => hunk.lines.every((line, i) => { + var _a2; + return line.startsWith("\\") || line.endsWith("\r") || ((_a2 = hunk.lines[i + 1]) === null || _a2 === void 0 ? void 0 : _a2.startsWith("\\")); + }))); +} + +// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/parse.js +function parsePatch(uniDiff) { + const diffstr = uniDiff.split(/\n/), list = []; + let i = 0; + function parseIndex() { + const index = {}; + list.push(index); + while (i < diffstr.length) { + const line = diffstr[i]; + if (/^(---|\+\+\+|@@)\s/.test(line)) { + break; + } + const headerMatch = /^(?:Index:|diff(?: -r \w+)+)\s+/.exec(line); + if (headerMatch) { + index.index = line.substring(headerMatch[0].length).trim(); + } + i++; + } + parseFileHeader(index); + parseFileHeader(index); + index.hunks = []; + while (i < diffstr.length) { + const line = diffstr[i]; + if (/^(Index:\s|diff\s|---\s|\+\+\+\s|===================================================================)/.test(line)) { + break; + } else if (/^@@/.test(line)) { + index.hunks.push(parseHunk()); + } else if (line) { + throw new Error("Unknown line " + (i + 1) + " " + JSON.stringify(line)); + } else { + i++; } - yield [name, value]; } } -} -var buildHeaders3 = (newHeaders) => { - const targetHeaders = new Headers(); - const nullHeaders = /* @__PURE__ */ new Set(); - for (const headers of newHeaders) { - const seenHeaders = /* @__PURE__ */ new Set(); - for (const [name, value] of iterateHeaders3(headers)) { - const lowerName = name.toLowerCase(); - if (!seenHeaders.has(lowerName)) { - targetHeaders.delete(name); - seenHeaders.add(lowerName); + function parseFileHeader(index) { + const fileHeaderMatch = /^(---|\+\+\+)\s+/.exec(diffstr[i]); + if (fileHeaderMatch) { + const prefix = fileHeaderMatch[1], data = diffstr[i].substring(3).trim().split(" ", 2), header = (data[1] || "").trim(); + let fileName = data[0].replace(/\\\\/g, "\\"); + if (fileName.startsWith('"') && fileName.endsWith('"')) { + fileName = fileName.substr(1, fileName.length - 2); } - if (value === null) { - targetHeaders.delete(name); - nullHeaders.add(lowerName); + if (prefix === "---") { + index.oldFileName = fileName; + index.oldHeader = header; } else { - targetHeaders.append(name, value); - nullHeaders.delete(lowerName); + index.newFileName = fileName; + index.newHeader = header; } + i++; } } - return { [brand_privateNullableHeaders3]: true, values: targetHeaders, nulls: nullHeaders }; -}; - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/env.mjs -var readEnv3 = (env) => { - if (typeof globalThis.process !== "undefined") { - return globalThis.process.env?.[env]?.trim() ?? void 0; + function parseHunk() { + var _a2; + const chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); + const hunk = { + oldStart: +chunkHeader[1], + oldLines: typeof chunkHeader[2] === "undefined" ? 1 : +chunkHeader[2], + newStart: +chunkHeader[3], + newLines: typeof chunkHeader[4] === "undefined" ? 1 : +chunkHeader[4], + lines: [] + }; + if (hunk.oldLines === 0) { + hunk.oldStart += 1; + } + if (hunk.newLines === 0) { + hunk.newStart += 1; + } + let addCount = 0, removeCount = 0; + for (; i < diffstr.length && (removeCount < hunk.oldLines || addCount < hunk.newLines || ((_a2 = diffstr[i]) === null || _a2 === void 0 ? void 0 : _a2.startsWith("\\"))); i++) { + const operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? " " : diffstr[i][0]; + if (operation === "+" || operation === "-" || operation === " " || operation === "\\") { + hunk.lines.push(diffstr[i]); + if (operation === "+") { + addCount++; + } else if (operation === "-") { + removeCount++; + } else if (operation === " ") { + addCount++; + removeCount++; + } + } else { + throw new Error(`Hunk at line ${chunkHeaderIndex + 1} contained invalid line ${diffstr[i]}`); + } + } + if (!addCount && hunk.newLines === 1) { + hunk.newLines = 0; + } + if (!removeCount && hunk.oldLines === 1) { + hunk.oldLines = 0; + } + if (addCount !== hunk.newLines) { + throw new Error("Added line count did not match for hunk at line " + (chunkHeaderIndex + 1)); + } + if (removeCount !== hunk.oldLines) { + throw new Error("Removed line count did not match for hunk at line " + (chunkHeaderIndex + 1)); + } + return hunk; } - if (typeof globalThis.Deno !== "undefined") { - return globalThis.Deno.env?.get?.(env)?.trim(); + while (i < diffstr.length) { + parseIndex(); } - return void 0; -}; + return list; +} -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/lib/unwrap.mjs -async function unwrapFile(value) { - if (value === null) { - return null; +// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/util/distance-iterator.js +function distance_iterator_default(start, minLine, maxLine) { + let wantForward = true, backwardExhausted = false, forwardExhausted = false, localOffset = 1; + return function iterator() { + if (wantForward && !forwardExhausted) { + if (backwardExhausted) { + localOffset++; + } else { + wantForward = false; + } + if (start + localOffset <= maxLine) { + return start + localOffset; + } + forwardExhausted = true; + } + if (!backwardExhausted) { + if (!forwardExhausted) { + wantForward = true; + } + if (minLine <= start - localOffset) { + return start - localOffset++; + } + backwardExhausted = true; + return iterator(); + } + return void 0; + }; +} + +// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/apply.js +function applyPatch(source, patch, options = {}) { + let patches; + if (typeof patch === "string") { + patches = parsePatch(patch); + } else if (Array.isArray(patch)) { + patches = patch; + } else { + patches = [patch]; } - if (value.type === "content") { - return value.content; + if (patches.length > 1) { + throw new Error("applyPatch only works with a single input."); } - const response = await fetch(value.url); - return response.text(); + return applyStructuredPatch(source, patches[0], options); } - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/client.mjs -var _Stainless_instances; -var _a; -var _Stainless_encoder; -var _Stainless_baseURLOverridden; -var environments = { - production: "https://api.stainless.com", - staging: "https://staging.stainless.com" -}; -var Stainless = class { - /** - * API Client for interfacing with the Stainless API. - * - * @param {string | null | undefined} [opts.apiKey=process.env['STAINLESS_API_KEY'] ?? null] - * @param {string | null | undefined} [opts.project] - * @param {Environment} [opts.environment=production] - Specifies the environment URL to use for the API. - * @param {string} [opts.baseURL=process.env['STAINLESS_BASE_URL'] ?? https://api.stainless.com] - Override the default base URL for the API. - * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. - * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. - * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. - * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. - * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. - * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. - */ - constructor({ baseURL = readEnv3("STAINLESS_BASE_URL"), apiKey = readEnv3("STAINLESS_API_KEY") ?? null, project = null, ...opts } = {}) { - _Stainless_instances.add(this); - _Stainless_encoder.set(this, void 0); - this.projects = new Projects5(this); - this.builds = new Builds2(this); - this.orgs = new Orgs3(this); - this.user = new User(this); - const options = { - apiKey, - project, - ...opts, - baseURL, - environment: opts.environment ?? "production" - }; - if (baseURL && opts.environment) { - throw new StainlessError("Ambiguous URL; The `baseURL` option (or STAINLESS_BASE_URL env var) and the `environment` option are given. If you want to use the environment you must pass baseURL: null"); +function applyStructuredPatch(source, patch, options = {}) { + if (options.autoConvertLineEndings || options.autoConvertLineEndings == null) { + if (hasOnlyWinLineEndings(source) && isUnix(patch)) { + patch = unixToWin(patch); + } else if (hasOnlyUnixLineEndings(source) && isWin(patch)) { + patch = winToUnix(patch); } - this.baseURL = options.baseURL || environments[options.environment || "production"]; - this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT; - this.logger = options.logger ?? console; - const defaultLogLevel = "warn"; - this.logLevel = defaultLogLevel; - this.logLevel = parseLogLevel3(options.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel3(readEnv3("STAINLESS_LOG"), "process.env['STAINLESS_LOG']", this) ?? defaultLogLevel; - this.fetchOptions = options.fetchOptions; - this.maxRetries = options.maxRetries ?? 2; - this.fetch = options.fetch ?? getDefaultFetch3(); - __classPrivateFieldSet3(this, _Stainless_encoder, FallbackEncoder3, "f"); - this._options = options; - this.apiKey = apiKey; - this.project = project; } - /** - * Create a new client instance re-using the same options given to the current client with optional overriding. - */ - withOptions(options) { - const client = new this.constructor({ - ...this._options, - environment: options.environment ? options.environment : void 0, - baseURL: options.environment ? void 0 : this.baseURL, - maxRetries: this.maxRetries, - timeout: this.timeout, - logger: this.logger, - logLevel: this.logLevel, - fetch: this.fetch, - fetchOptions: this.fetchOptions, - apiKey: this.apiKey, - project: this.project, - ...options - }); - return client; + const lines = source.split("\n"), hunks = patch.hunks, compareLine = options.compareLine || ((lineNumber, line, operation, patchContent) => line === patchContent), fuzzFactor = options.fuzzFactor || 0; + let minLine = 0; + if (fuzzFactor < 0 || !Number.isInteger(fuzzFactor)) { + throw new Error("fuzzFactor must be a non-negative integer"); } - defaultQuery() { - return this._options.defaultQuery; + if (!hunks.length) { + return source; } - validateHeaders({ values, nulls }) { - if (this.apiKey && values.get("authorization")) { - return; + let prevLine = "", removeEOFNL = false, addEOFNL = false; + for (let i = 0; i < hunks[hunks.length - 1].lines.length; i++) { + const line = hunks[hunks.length - 1].lines[i]; + if (line[0] == "\\") { + if (prevLine[0] == "+") { + removeEOFNL = true; + } else if (prevLine[0] == "-") { + addEOFNL = true; + } + } + prevLine = line; + } + if (removeEOFNL) { + if (addEOFNL) { + if (!fuzzFactor && lines[lines.length - 1] == "") { + return false; + } + } else if (lines[lines.length - 1] == "") { + lines.pop(); + } else if (!fuzzFactor) { + return false; } - if (nulls.has("authorization")) { - return; + } else if (addEOFNL) { + if (lines[lines.length - 1] != "") { + lines.push(""); + } else if (!fuzzFactor) { + return false; } - throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "Authorization" headers to be explicitly omitted'); } - async authHeaders(opts) { - if (this.apiKey == null) { - return void 0; + function applyHunk(hunkLines, toPos, maxErrors, hunkLinesI = 0, lastContextLineMatched = true, patchedLines = [], patchedLinesLength = 0) { + let nConsecutiveOldContextLines = 0; + let nextContextLineMustMatch = false; + for (; hunkLinesI < hunkLines.length; hunkLinesI++) { + const hunkLine = hunkLines[hunkLinesI], operation = hunkLine.length > 0 ? hunkLine[0] : " ", content = hunkLine.length > 0 ? hunkLine.substr(1) : hunkLine; + if (operation === "-") { + if (compareLine(toPos + 1, lines[toPos], operation, content)) { + toPos++; + nConsecutiveOldContextLines = 0; + } else { + if (!maxErrors || lines[toPos] == null) { + return null; + } + patchedLines[patchedLinesLength] = lines[toPos]; + return applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1); + } + } + if (operation === "+") { + if (!lastContextLineMatched) { + return null; + } + patchedLines[patchedLinesLength] = content; + patchedLinesLength++; + nConsecutiveOldContextLines = 0; + nextContextLineMustMatch = true; + } + if (operation === " ") { + nConsecutiveOldContextLines++; + patchedLines[patchedLinesLength] = lines[toPos]; + if (compareLine(toPos + 1, lines[toPos], operation, content)) { + patchedLinesLength++; + lastContextLineMatched = true; + nextContextLineMustMatch = false; + toPos++; + } else { + if (nextContextLineMustMatch || !maxErrors) { + return null; + } + return lines[toPos] && (applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI + 1, false, patchedLines, patchedLinesLength + 1) || applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1)) || applyHunk(hunkLines, toPos, maxErrors - 1, hunkLinesI + 1, false, patchedLines, patchedLinesLength); + } + } } - return buildHeaders3([{ Authorization: `Bearer ${this.apiKey}` }]); - } - stringifyQuery(query) { - return stringifyQuery(query); - } - getUserAgent() { - return `${this.constructor.name}/JS ${VERSION3}`; - } - defaultIdempotencyKey() { - return `stainless-node-retry-${uuid43()}`; - } - makeStatusError(status, error, message, headers) { - return APIError3.generate(status, error, message, headers); + patchedLinesLength -= nConsecutiveOldContextLines; + toPos -= nConsecutiveOldContextLines; + patchedLines.length = patchedLinesLength; + return { + patchedLines, + oldLineLastI: toPos - 1 + }; } - buildURL(path7, query, defaultBaseURL) { - const baseURL = !__classPrivateFieldGet3(this, _Stainless_instances, "m", _Stainless_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL; - const url = isAbsoluteURL3(path7) ? new URL(path7) : new URL(baseURL + (baseURL.endsWith("/") && path7.startsWith("/") ? path7.slice(1) : path7)); - const defaultQuery = this.defaultQuery(); - if (!isEmptyObj3(defaultQuery)) { - query = { ...defaultQuery, ...query }; + const resultLines = []; + let prevHunkOffset = 0; + for (let i = 0; i < hunks.length; i++) { + const hunk = hunks[i]; + let hunkResult; + const maxLine = lines.length - hunk.oldLines + fuzzFactor; + let toPos; + for (let maxErrors = 0; maxErrors <= fuzzFactor; maxErrors++) { + toPos = hunk.oldStart + prevHunkOffset - 1; + const iterator = distance_iterator_default(toPos, minLine, maxLine); + for (; toPos !== void 0; toPos = iterator()) { + hunkResult = applyHunk(hunk.lines, toPos, maxErrors); + if (hunkResult) { + break; + } + } + if (hunkResult) { + break; + } } - if (typeof query === "object" && query && !Array.isArray(query)) { - url.search = this.stringifyQuery(query); + if (!hunkResult) { + return false; } - return url.toString(); - } - /** - * Used as a callback for mutating the given `FinalRequestOptions` object. - */ - async prepareOptions(options) { - } - /** - * Used as a callback for mutating the given `RequestInit` object. - * - * This is useful for cases where you want to add certain headers based off of - * the request properties, e.g. `method` or `url`. - */ - async prepareRequest(request, { url, options }) { - } - get(path7, opts) { - return this.methodRequest("get", path7, opts); - } - post(path7, opts) { - return this.methodRequest("post", path7, opts); + for (let i2 = minLine; i2 < toPos; i2++) { + resultLines.push(lines[i2]); + } + for (let i2 = 0; i2 < hunkResult.patchedLines.length; i2++) { + const line = hunkResult.patchedLines[i2]; + resultLines.push(line); + } + minLine = hunkResult.oldLineLastI + 1; + prevHunkOffset = toPos + 1 - hunk.oldStart; } - patch(path7, opts) { - return this.methodRequest("patch", path7, opts); + for (let i = minLine; i < lines.length; i++) { + resultLines.push(lines[i]); } - put(path7, opts) { - return this.methodRequest("put", path7, opts); + return resultLines.join("\n"); +} + +// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js +var INCLUDE_HEADERS = { + includeIndex: true, + includeUnderline: true, + includeFileHeaders: true +}; +function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + let optionsObj; + if (!options) { + optionsObj = {}; + } else if (typeof options === "function") { + optionsObj = { callback: options }; + } else { + optionsObj = options; } - delete(path7, opts) { - return this.methodRequest("delete", path7, opts); + if (typeof optionsObj.context === "undefined") { + optionsObj.context = 4; } - methodRequest(method, path7, opts) { - return this.request(Promise.resolve(opts).then((opts2) => { - return { method, path: path7, ...opts2 }; - })); + const context = optionsObj.context; + if (optionsObj.newlineIsToken) { + throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions"); } - request(options, remainingRetries = null) { - return new APIPromise3(this, this.makeRequest(options, remainingRetries, void 0)); + if (!optionsObj.callback) { + return diffLinesResultToPatch(diffLines(oldStr, newStr, optionsObj)); + } else { + const { callback } = optionsObj; + diffLines(oldStr, newStr, Object.assign(Object.assign({}, optionsObj), { callback: (diff) => { + const patch = diffLinesResultToPatch(diff); + callback(patch); + } })); } - async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { - const options = await optionsInput; - const maxRetries = options.maxRetries ?? this.maxRetries; - if (retriesRemaining == null) { - retriesRemaining = maxRetries; + function diffLinesResultToPatch(diff) { + if (!diff) { + return; } - await this.prepareOptions(options); - const { req, url, timeout } = await this.buildRequest(options, { - retryCount: maxRetries - retriesRemaining - }); - await this.prepareRequest(req, { url, options }); - const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0"); - const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`; - const startTime = Date.now(); - loggerFor3(this).debug(`[${requestLogID}] sending request`, formatRequestDetails3({ - retryOfRequestLogID, - method: options.method, - url, - options, - headers: req.headers - })); - if (options.signal?.aborted) { - throw new APIUserAbortError3(); + diff.push({ value: "", lines: [] }); + function contextLines(lines) { + return lines.map(function(entry) { + return " " + entry; + }); } - const controller = new AbortController(); - const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError3); - const headersTime = Date.now(); - if (response instanceof globalThis.Error) { - const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; - if (options.signal?.aborted) { - throw new APIUserAbortError3(); - } - const isTimeout = isAbortError3(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : "")); - if (retriesRemaining) { - loggerFor3(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`); - loggerFor3(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails3({ - retryOfRequestLogID, - url, - durationMs: headersTime - startTime, - message: response.message - })); - return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); - } - loggerFor3(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`); - loggerFor3(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails3({ - retryOfRequestLogID, - url, - durationMs: headersTime - startTime, - message: response.message - })); - if (isTimeout) { - throw new APIConnectionTimeoutError3(); + const hunks = []; + let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; + for (let i = 0; i < diff.length; i++) { + const current = diff[i], lines = current.lines || splitLines(current.value); + current.lines = lines; + if (current.added || current.removed) { + if (!oldRangeStart) { + const prev = diff[i - 1]; + oldRangeStart = oldLine; + newRangeStart = newLine; + if (prev) { + curRange = context > 0 ? contextLines(prev.lines.slice(-context)) : []; + oldRangeStart -= curRange.length; + newRangeStart -= curRange.length; + } + } + for (const line of lines) { + curRange.push((current.added ? "+" : "-") + line); + } + if (current.added) { + newLine += lines.length; + } else { + oldLine += lines.length; + } + } else { + if (oldRangeStart) { + if (lines.length <= context * 2 && i < diff.length - 2) { + for (const line of contextLines(lines)) { + curRange.push(line); + } + } else { + const contextSize = Math.min(lines.length, context); + for (const line of contextLines(lines.slice(0, contextSize))) { + curRange.push(line); + } + const hunk = { + oldStart: oldRangeStart, + oldLines: oldLine - oldRangeStart + contextSize, + newStart: newRangeStart, + newLines: newLine - newRangeStart + contextSize, + lines: curRange + }; + hunks.push(hunk); + oldRangeStart = 0; + newRangeStart = 0; + curRange = []; + } + } + oldLine += lines.length; + newLine += lines.length; } - throw new APIConnectionError3({ cause: response }); } - const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`; - if (!response.ok) { - const shouldRetry = await this.shouldRetry(response); - if (retriesRemaining && shouldRetry) { - const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`; - await CancelReadableStream3(response.body); - loggerFor3(this).info(`${responseInfo} - ${retryMessage2}`); - loggerFor3(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails3({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - durationMs: headersTime - startTime - })); - return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); + for (const hunk of hunks) { + for (let i = 0; i < hunk.lines.length; i++) { + if (hunk.lines[i].endsWith("\n")) { + hunk.lines[i] = hunk.lines[i].slice(0, -1); + } else { + hunk.lines.splice(i + 1, 0, "\\ No newline at end of file"); + i++; + } } - const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; - loggerFor3(this).info(`${responseInfo} - ${retryMessage}`); - const errText = await response.text().catch((err2) => castToError3(err2).message); - const errJSON = safeJSON3(errText); - const errMessage = errJSON ? void 0 : errText; - loggerFor3(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails3({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - message: errMessage, - durationMs: Date.now() - startTime - })); - const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); - throw err; } - loggerFor3(this).info(responseInfo); - loggerFor3(this).debug(`[${requestLogID}] response start`, formatRequestDetails3({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - durationMs: headersTime - startTime - })); - return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; - } - getAPIList(path7, Page2, opts) { - return this.requestAPIList(Page2, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path7, ...opts2 })) : { method: "get", path: path7, ...opts }); + return { + oldFileName, + newFileName, + oldHeader, + newHeader, + hunks + }; } - requestAPIList(Page2, options) { - const request = this.makeRequest(options, null, void 0); - return new PagePromise2(this, request, Page2); +} +function formatPatch(patch, headerOptions) { + if (!headerOptions) { + headerOptions = INCLUDE_HEADERS; } - async fetchWithTimeout(url, init, ms, controller) { - const { signal, method, ...options } = init || {}; - const abort = this._makeAbort(controller); - if (signal) - signal.addEventListener("abort", abort, { once: true }); - const timeout = setTimeout(abort, ms); - const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body; - const fetchOptions = { - signal: controller.signal, - ...isReadableBody ? { duplex: "half" } : {}, - method: "GET", - ...options - }; - if (method) { - fetchOptions.method = method.toUpperCase(); - } - try { - return await this.fetch.call(void 0, url, fetchOptions); - } finally { - clearTimeout(timeout); + if (Array.isArray(patch)) { + if (patch.length > 1 && !headerOptions.includeFileHeaders) { + throw new Error("Cannot omit file headers on a multi-file patch. (The result would be unparseable; how would a tool trying to apply the patch know which changes are to which file?)"); } + return patch.map((p) => formatPatch(p, headerOptions)).join("\n"); } - async shouldRetry(response) { - const shouldRetryHeader = response.headers.get("x-should-retry"); - if (shouldRetryHeader === "true") - return true; - if (shouldRetryHeader === "false") - return false; - if (response.status === 408) - return true; - if (response.status === 409) - return true; - if (response.status === 429) - return true; - if (response.status >= 500) - return true; - return false; + const ret = []; + if (headerOptions.includeIndex && patch.oldFileName == patch.newFileName) { + ret.push("Index: " + patch.oldFileName); } - async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { - let timeoutMillis; - const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms"); - if (retryAfterMillisHeader) { - const timeoutMs = parseFloat(retryAfterMillisHeader); - if (!Number.isNaN(timeoutMs)) { - timeoutMillis = timeoutMs; - } + if (headerOptions.includeUnderline) { + ret.push("==================================================================="); + } + if (headerOptions.includeFileHeaders) { + ret.push("--- " + patch.oldFileName + (typeof patch.oldHeader === "undefined" ? "" : " " + patch.oldHeader)); + ret.push("+++ " + patch.newFileName + (typeof patch.newHeader === "undefined" ? "" : " " + patch.newHeader)); + } + for (let i = 0; i < patch.hunks.length; i++) { + const hunk = patch.hunks[i]; + if (hunk.oldLines === 0) { + hunk.oldStart -= 1; } - const retryAfterHeader = responseHeaders?.get("retry-after"); - if (retryAfterHeader && !timeoutMillis) { - const timeoutSeconds = parseFloat(retryAfterHeader); - if (!Number.isNaN(timeoutSeconds)) { - timeoutMillis = timeoutSeconds * 1e3; - } else { - timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); - } + if (hunk.newLines === 0) { + hunk.newStart -= 1; } - if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1e3)) { - const maxRetries = options.maxRetries ?? this.maxRetries; - timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + ret.push("@@ -" + hunk.oldStart + "," + hunk.oldLines + " +" + hunk.newStart + "," + hunk.newLines + " @@"); + for (const line of hunk.lines) { + ret.push(line); } - await sleep3(timeoutMillis); - return this.makeRequest(options, retriesRemaining - 1, requestLogID); } - calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { - const initialRetryDelay = 0.5; - const maxRetryDelay = 8; - const numRetries = maxRetries - retriesRemaining; - const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); - const jitter = 1 - Math.random() * 0.25; - return sleepSeconds * jitter * 1e3; - } - async buildRequest(inputOptions, { retryCount = 0 } = {}) { - const options = { ...inputOptions }; - const { method, path: path7, query, defaultBaseURL } = options; - const url = this.buildURL(path7, query, defaultBaseURL); - if ("timeout" in options) - validatePositiveInteger3("timeout", options.timeout); - options.timeout = options.timeout ?? this.timeout; - const { bodyHeaders, body } = this.buildBody({ options }); - const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); - const req = { - method, - headers: reqHeaders, - ...options.signal && { signal: options.signal }, - ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" }, - ...body && { body }, - ...this.fetchOptions ?? {}, - ...options.fetchOptions ?? {} - }; - return { req, url, timeout: options.timeout }; + return ret.join("\n") + "\n"; +} +function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + if (typeof options === "function") { + options = { callback: options }; } - async buildHeaders({ options, method, bodyHeaders, retryCount }) { - let idempotencyHeaders = {}; - if (this.idempotencyHeader && method !== "get") { - if (!options.idempotencyKey) - options.idempotencyKey = this.defaultIdempotencyKey(); - idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; + if (!(options === null || options === void 0 ? void 0 : options.callback)) { + const patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); + if (!patchObj) { + return; } - const headers = buildHeaders3([ - idempotencyHeaders, - { - Accept: "application/json", - "User-Agent": this.getUserAgent(), - "X-Stainless-Retry-Count": String(retryCount), - ...options.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options.timeout / 1e3)) } : {}, - ...getPlatformHeaders3() - }, - await this.authHeaders(options), - this._options.defaultHeaders, - bodyHeaders, - options.headers - ]); - this.validateHeaders(headers); - return headers.values; - } - _makeAbort(controller) { - return () => controller.abort(); + return formatPatch(patchObj, options === null || options === void 0 ? void 0 : options.headerOptions); + } else { + const { callback } = options; + structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, Object.assign(Object.assign({}, options), { callback: (patchObj) => { + if (!patchObj) { + callback(void 0); + } else { + callback(formatPatch(patchObj, options.headerOptions)); + } + } })); } - buildBody({ options: { body, headers: rawHeaders } }) { - if (!body) { - return { bodyHeaders: void 0, body: void 0 }; - } - const headers = buildHeaders3([rawHeaders]); - if ( - // Pass raw type verbatim - ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && // Preserve legacy string encoding behavior for now - headers.values.has("content-type") || // `Blob` is superset of `File` - globalThis.Blob && body instanceof globalThis.Blob || // `FormData` -> `multipart/form-data` - body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded` - body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`) - globalThis.ReadableStream && body instanceof globalThis.ReadableStream - ) { - return { bodyHeaders: void 0, body }; - } else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) { - return { bodyHeaders: void 0, body: ReadableStreamFrom3(body) }; - } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") { - return { - bodyHeaders: { "content-type": "application/x-www-form-urlencoded" }, - body: this.stringifyQuery(body) - }; - } else { - return __classPrivateFieldGet3(this, _Stainless_encoder, "f").call(this, { body, headers }); - } +} +function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { + return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); +} +function splitLines(text) { + const hasTrailingNl = text.endsWith("\n"); + const result = text.split("\n").map((line) => line + "\n"); + if (hasTrailingNl) { + result.pop(); + } else { + result.push(result.pop().slice(0, -1)); } -}; -_a = Stainless, _Stainless_encoder = /* @__PURE__ */ new WeakMap(), _Stainless_instances = /* @__PURE__ */ new WeakSet(), _Stainless_baseURLOverridden = function _Stainless_baseURLOverridden2() { - return this.baseURL !== environments[this._options.environment || "production"]; -}; -Stainless.Stainless = _a; -Stainless.DEFAULT_TIMEOUT = 6e4; -Stainless.StainlessError = StainlessError; -Stainless.APIError = APIError3; -Stainless.APIConnectionError = APIConnectionError3; -Stainless.APIConnectionTimeoutError = APIConnectionTimeoutError3; -Stainless.APIUserAbortError = APIUserAbortError3; -Stainless.NotFoundError = NotFoundError3; -Stainless.ConflictError = ConflictError3; -Stainless.RateLimitError = RateLimitError3; -Stainless.BadRequestError = BadRequestError3; -Stainless.AuthenticationError = AuthenticationError3; -Stainless.InternalServerError = InternalServerError3; -Stainless.PermissionDeniedError = PermissionDeniedError3; -Stainless.UnprocessableEntityError = UnprocessableEntityError3; -Stainless.toFile = toFile3; -Stainless.unwrapFile = unwrapFile; -Stainless.Projects = Projects5; -Stainless.Builds = Builds2; -Stainless.Orgs = Orgs3; -Stainless.User = User; + return result; +} // package.json var package_default = { @@ -20010,7 +20027,8 @@ function wrapAction(actionType, fn) { actionType, successOrError: { result: "success" } }); - } catch (error) { + } catch (rawError) { + const error = maybeToActionError(rawError); logger.fatal("Error in action:", error); if (stainless) { await maybeReportResult({ diff --git a/dist/prepareCombine.js b/dist/prepareCombine.js index a1697a8..2065537 100644 --- a/dist/prepareCombine.js +++ b/dist/prepareCombine.js @@ -102,17 +102,17 @@ var require_visit = __commonJS({ visit.BREAK = BREAK; visit.SKIP = SKIP; visit.REMOVE = REMOVE; - function visit_(key, node, visitor, path5) { - const ctrl = callVisitor(key, node, visitor, path5); + function visit_(key, node, visitor, path6) { + const ctrl = callVisitor(key, node, visitor, path6); if (identity.isNode(ctrl) || identity.isPair(ctrl)) { - replaceNode(key, path5, ctrl); - return visit_(key, ctrl, visitor, path5); + replaceNode(key, path6, ctrl); + return visit_(key, ctrl, visitor, path6); } if (typeof ctrl !== "symbol") { if (identity.isCollection(node)) { - path5 = Object.freeze(path5.concat(node)); + path6 = Object.freeze(path6.concat(node)); for (let i = 0; i < node.items.length; ++i) { - const ci = visit_(i, node.items[i], visitor, path5); + const ci = visit_(i, node.items[i], visitor, path6); if (typeof ci === "number") i = ci - 1; else if (ci === BREAK) @@ -123,13 +123,13 @@ var require_visit = __commonJS({ } } } else if (identity.isPair(node)) { - path5 = Object.freeze(path5.concat(node)); - const ck = visit_("key", node.key, visitor, path5); + path6 = Object.freeze(path6.concat(node)); + const ck = visit_("key", node.key, visitor, path6); if (ck === BREAK) return BREAK; else if (ck === REMOVE) node.key = null; - const cv = visit_("value", node.value, visitor, path5); + const cv = visit_("value", node.value, visitor, path6); if (cv === BREAK) return BREAK; else if (cv === REMOVE) @@ -150,17 +150,17 @@ var require_visit = __commonJS({ visitAsync.BREAK = BREAK; visitAsync.SKIP = SKIP; visitAsync.REMOVE = REMOVE; - async function visitAsync_(key, node, visitor, path5) { - const ctrl = await callVisitor(key, node, visitor, path5); + async function visitAsync_(key, node, visitor, path6) { + const ctrl = await callVisitor(key, node, visitor, path6); if (identity.isNode(ctrl) || identity.isPair(ctrl)) { - replaceNode(key, path5, ctrl); - return visitAsync_(key, ctrl, visitor, path5); + replaceNode(key, path6, ctrl); + return visitAsync_(key, ctrl, visitor, path6); } if (typeof ctrl !== "symbol") { if (identity.isCollection(node)) { - path5 = Object.freeze(path5.concat(node)); + path6 = Object.freeze(path6.concat(node)); for (let i = 0; i < node.items.length; ++i) { - const ci = await visitAsync_(i, node.items[i], visitor, path5); + const ci = await visitAsync_(i, node.items[i], visitor, path6); if (typeof ci === "number") i = ci - 1; else if (ci === BREAK) @@ -171,13 +171,13 @@ var require_visit = __commonJS({ } } } else if (identity.isPair(node)) { - path5 = Object.freeze(path5.concat(node)); - const ck = await visitAsync_("key", node.key, visitor, path5); + path6 = Object.freeze(path6.concat(node)); + const ck = await visitAsync_("key", node.key, visitor, path6); if (ck === BREAK) return BREAK; else if (ck === REMOVE) node.key = null; - const cv = await visitAsync_("value", node.value, visitor, path5); + const cv = await visitAsync_("value", node.value, visitor, path6); if (cv === BREAK) return BREAK; else if (cv === REMOVE) @@ -204,23 +204,23 @@ var require_visit = __commonJS({ } return visitor; } - function callVisitor(key, node, visitor, path5) { + function callVisitor(key, node, visitor, path6) { if (typeof visitor === "function") - return visitor(key, node, path5); + return visitor(key, node, path6); if (identity.isMap(node)) - return visitor.Map?.(key, node, path5); + return visitor.Map?.(key, node, path6); if (identity.isSeq(node)) - return visitor.Seq?.(key, node, path5); + return visitor.Seq?.(key, node, path6); if (identity.isPair(node)) - return visitor.Pair?.(key, node, path5); + return visitor.Pair?.(key, node, path6); if (identity.isScalar(node)) - return visitor.Scalar?.(key, node, path5); + return visitor.Scalar?.(key, node, path6); if (identity.isAlias(node)) - return visitor.Alias?.(key, node, path5); + return visitor.Alias?.(key, node, path6); return void 0; } - function replaceNode(key, path5, node) { - const parent = path5[path5.length - 1]; + function replaceNode(key, path6, node) { + const parent = path6[path6.length - 1]; if (identity.isCollection(parent)) { parent.items[key] = node; } else if (identity.isPair(parent)) { @@ -828,10 +828,10 @@ var require_Collection = __commonJS({ var createNode = require_createNode(); var identity = require_identity(); var Node = require_Node(); - function collectionFromPath(schema, path5, value) { + function collectionFromPath(schema, path6, value) { let v = value; - for (let i = path5.length - 1; i >= 0; --i) { - const k = path5[i]; + for (let i = path6.length - 1; i >= 0; --i) { + const k = path6[i]; if (typeof k === "number" && Number.isInteger(k) && k >= 0) { const a = []; a[k] = v; @@ -850,7 +850,7 @@ var require_Collection = __commonJS({ sourceObjects: /* @__PURE__ */ new Map() }); } - var isEmptyPath = (path5) => path5 == null || typeof path5 === "object" && !!path5[Symbol.iterator]().next().done; + var isEmptyPath = (path6) => path6 == null || typeof path6 === "object" && !!path6[Symbol.iterator]().next().done; var Collection = class extends Node.NodeBase { constructor(type, schema) { super(type); @@ -880,11 +880,11 @@ var require_Collection = __commonJS({ * be a Pair instance or a `{ key, value }` object, which may not have a key * that already exists in the map. */ - addIn(path5, value) { - if (isEmptyPath(path5)) + addIn(path6, value) { + if (isEmptyPath(path6)) this.add(value); else { - const [key, ...rest] = path5; + const [key, ...rest] = path6; const node = this.get(key, true); if (identity.isCollection(node)) node.addIn(rest, value); @@ -898,8 +898,8 @@ var require_Collection = __commonJS({ * Removes a value from the collection. * @returns `true` if the item was found and removed. */ - deleteIn(path5) { - const [key, ...rest] = path5; + deleteIn(path6) { + const [key, ...rest] = path6; if (rest.length === 0) return this.delete(key); const node = this.get(key, true); @@ -913,8 +913,8 @@ var require_Collection = __commonJS({ * scalar values from their surrounding node; to disable set `keepScalar` to * `true` (collections are always returned intact). */ - getIn(path5, keepScalar) { - const [key, ...rest] = path5; + getIn(path6, keepScalar) { + const [key, ...rest] = path6; const node = this.get(key, true); if (rest.length === 0) return !keepScalar && identity.isScalar(node) ? node.value : node; @@ -932,8 +932,8 @@ var require_Collection = __commonJS({ /** * Checks if the collection includes a value with the key `key`. */ - hasIn(path5) { - const [key, ...rest] = path5; + hasIn(path6) { + const [key, ...rest] = path6; if (rest.length === 0) return this.has(key); const node = this.get(key, true); @@ -943,8 +943,8 @@ var require_Collection = __commonJS({ * Sets a value in this collection. For `!!set`, `value` needs to be a * boolean to add/remove the item from the set. */ - setIn(path5, value) { - const [key, ...rest] = path5; + setIn(path6, value) { + const [key, ...rest] = path6; if (rest.length === 0) { this.set(key, value); } else { @@ -1132,16 +1132,16 @@ var require_stringifyString = __commonJS({ function lineLengthOverLimit(str, lineWidth, indentLength) { if (!lineWidth || lineWidth < 0) return false; - const limit = lineWidth - indentLength; + const limit2 = lineWidth - indentLength; const strLen = str.length; - if (strLen <= limit) + if (strLen <= limit2) return false; for (let i = 0, start = 0; i < strLen; ++i) { if (str[i] === "\n") { - if (i - start > limit) + if (i - start > limit2) return true; start = i + 1; - if (strLen - start <= limit) + if (strLen - start <= limit2) return false; } } @@ -1490,7 +1490,7 @@ var require_stringify = __commonJS({ props.push(doc.directives.tagString(tag)); return props.join(" "); } - function stringify(item, ctx, onComment, onChompKeep) { + function stringify2(item, ctx, onComment, onChompKeep) { if (identity.isPair(item)) return item.toString(ctx, onComment, onChompKeep); if (identity.isAlias(item)) { @@ -1519,7 +1519,7 @@ var require_stringify = __commonJS({ ${ctx.indent}${str}`; } exports2.createStringifyContext = createStringifyContext; - exports2.stringify = stringify; + exports2.stringify = stringify2; } }); @@ -1529,7 +1529,7 @@ var require_stringifyPair = __commonJS({ "use strict"; var identity = require_identity(); var Scalar = require_Scalar(); - var stringify = require_stringify(); + var stringify2 = require_stringify(); var stringifyComment = require_stringifyComment(); function stringifyPair({ key, value }, ctx, onComment, onChompKeep) { const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; @@ -1551,7 +1551,7 @@ var require_stringifyPair = __commonJS({ }); let keyCommentDone = false; let chompKeep = false; - let str = stringify.stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true); + let str = stringify2.stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true); if (!explicitKey && !ctx.inFlow && str.length > 1024) { if (simpleKeys) throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); @@ -1603,7 +1603,7 @@ ${indent}:`; ctx.indent = ctx.indent.substring(2); } let valueCommentDone = false; - const valueStr = stringify.stringify(value, ctx, () => valueCommentDone = true, () => chompKeep = true); + const valueStr = stringify2.stringify(value, ctx, () => valueCommentDone = true, () => chompKeep = true); let ws = " "; if (keyComment || vsb || vcb) { ws = vsb ? "\n" : ""; @@ -1741,7 +1741,7 @@ var require_addPairToJSMap = __commonJS({ "use strict"; var log = require_log(); var merge = require_merge(); - var stringify = require_stringify(); + var stringify2 = require_stringify(); var identity = require_identity(); var toJS = require_toJS(); function addPairToJSMap(ctx, map, { key, value }) { @@ -1777,7 +1777,7 @@ var require_addPairToJSMap = __commonJS({ if (typeof jsKey !== "object") return String(jsKey); if (identity.isNode(key) && ctx?.doc) { - const strCtx = stringify.createStringifyContext(ctx.doc, {}); + const strCtx = stringify2.createStringifyContext(ctx.doc, {}); strCtx.anchors = /* @__PURE__ */ new Set(); for (const node of ctx.anchors.keys()) strCtx.anchors.add(node.anchor); @@ -1844,12 +1844,12 @@ var require_stringifyCollection = __commonJS({ "node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/stringify/stringifyCollection.js"(exports2) { "use strict"; var identity = require_identity(); - var stringify = require_stringify(); + var stringify2 = require_stringify(); var stringifyComment = require_stringifyComment(); function stringifyCollection(collection, ctx, options) { const flow = ctx.inFlow ?? collection.flow; - const stringify2 = flow ? stringifyFlowCollection : stringifyBlockCollection; - return stringify2(collection, ctx, options); + const stringify3 = flow ? stringifyFlowCollection : stringifyBlockCollection; + return stringify3(collection, ctx, options); } function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { const { indent, options: { commentString } } = ctx; @@ -1874,7 +1874,7 @@ var require_stringifyCollection = __commonJS({ } } chompKeep = false; - let str2 = stringify.stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true); + let str2 = stringify2.stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true); if (comment2) str2 += stringifyComment.lineComment(str2, itemIndent, commentString(comment2)); if (chompKeep && comment2) @@ -1941,7 +1941,7 @@ ${indent}${line}` : "\n"; } if (comment) reqNewline = true; - let str = stringify.stringify(item, itemCtx, () => comment = null); + let str = stringify2.stringify(item, itemCtx, () => comment = null); if (i < items.length - 1) str += ","; if (comment) @@ -3295,7 +3295,7 @@ var require_stringifyDocument = __commonJS({ "node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/stringify/stringifyDocument.js"(exports2) { "use strict"; var identity = require_identity(); - var stringify = require_stringify(); + var stringify2 = require_stringify(); var stringifyComment = require_stringifyComment(); function stringifyDocument(doc, options) { const lines = []; @@ -3310,7 +3310,7 @@ var require_stringifyDocument = __commonJS({ } if (hasDirectives) lines.push("---"); - const ctx = stringify.createStringifyContext(doc, options); + const ctx = stringify2.createStringifyContext(doc, options); const { commentString } = ctx.options; if (doc.commentBefore) { if (lines.length !== 1) @@ -3332,7 +3332,7 @@ var require_stringifyDocument = __commonJS({ contentComment = doc.contents.comment; } const onChompKeep = contentComment ? void 0 : () => chompKeep = true; - let body = stringify.stringify(doc.contents, ctx, () => contentComment = null, onChompKeep); + let body = stringify2.stringify(doc.contents, ctx, () => contentComment = null, onChompKeep); if (contentComment) body += stringifyComment.lineComment(body, "", commentString(contentComment)); if ((body[0] === "|" || body[0] === ">") && lines[lines.length - 1] === "---") { @@ -3340,7 +3340,7 @@ var require_stringifyDocument = __commonJS({ } else lines.push(body); } else { - lines.push(stringify.stringify(doc.contents, ctx)); + lines.push(stringify2.stringify(doc.contents, ctx)); } if (doc.directives?.docEnd) { if (doc.comment) { @@ -3448,9 +3448,9 @@ var require_Document = __commonJS({ this.contents.add(value); } /** Adds a value to the document. */ - addIn(path5, value) { + addIn(path6, value) { if (assertCollection(this.contents)) - this.contents.addIn(path5, value); + this.contents.addIn(path6, value); } /** * Create a new `Alias` node, ensuring that the target `node` has the required anchor. @@ -3525,14 +3525,14 @@ var require_Document = __commonJS({ * Removes a value from the document. * @returns `true` if the item was found and removed. */ - deleteIn(path5) { - if (Collection.isEmptyPath(path5)) { + deleteIn(path6) { + if (Collection.isEmptyPath(path6)) { if (this.contents == null) return false; this.contents = null; return true; } - return assertCollection(this.contents) ? this.contents.deleteIn(path5) : false; + return assertCollection(this.contents) ? this.contents.deleteIn(path6) : false; } /** * Returns item at `key`, or `undefined` if not found. By default unwraps @@ -3547,10 +3547,10 @@ var require_Document = __commonJS({ * scalar values from their surrounding node; to disable set `keepScalar` to * `true` (collections are always returned intact). */ - getIn(path5, keepScalar) { - if (Collection.isEmptyPath(path5)) + getIn(path6, keepScalar) { + if (Collection.isEmptyPath(path6)) return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents; - return identity.isCollection(this.contents) ? this.contents.getIn(path5, keepScalar) : void 0; + return identity.isCollection(this.contents) ? this.contents.getIn(path6, keepScalar) : void 0; } /** * Checks if the document includes a value with the key `key`. @@ -3561,10 +3561,10 @@ var require_Document = __commonJS({ /** * Checks if the document includes a value at `path`. */ - hasIn(path5) { - if (Collection.isEmptyPath(path5)) + hasIn(path6) { + if (Collection.isEmptyPath(path6)) return this.contents !== void 0; - return identity.isCollection(this.contents) ? this.contents.hasIn(path5) : false; + return identity.isCollection(this.contents) ? this.contents.hasIn(path6) : false; } /** * Sets a value in this document. For `!!set`, `value` needs to be a @@ -3581,13 +3581,13 @@ var require_Document = __commonJS({ * Sets a value in this document. For `!!set`, `value` needs to be a * boolean to add/remove the item from the set. */ - setIn(path5, value) { - if (Collection.isEmptyPath(path5)) { + setIn(path6, value) { + if (Collection.isEmptyPath(path6)) { this.contents = value; } else if (this.contents == null) { - this.contents = Collection.collectionFromPath(this.schema, Array.from(path5), value); + this.contents = Collection.collectionFromPath(this.schema, Array.from(path6), value); } else if (assertCollection(this.contents)) { - this.contents.setIn(path5, value); + this.contents.setIn(path6, value); } } /** @@ -5467,7 +5467,7 @@ var require_cst_scalar = __commonJS({ var require_cst_stringify = __commonJS({ "node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/parse/cst-stringify.js"(exports2) { "use strict"; - var stringify = (cst) => "type" in cst ? stringifyToken(cst) : stringifyItem(cst); + var stringify2 = (cst) => "type" in cst ? stringifyToken(cst) : stringifyItem(cst); function stringifyToken(token) { switch (token.type) { case "block-scalar": { @@ -5520,7 +5520,7 @@ var require_cst_stringify = __commonJS({ res += stringifyToken(value); return res; } - exports2.stringify = stringify; + exports2.stringify = stringify2; } }); @@ -5539,9 +5539,9 @@ var require_cst_visit = __commonJS({ visit.BREAK = BREAK; visit.SKIP = SKIP; visit.REMOVE = REMOVE; - visit.itemAtPath = (cst, path5) => { + visit.itemAtPath = (cst, path6) => { let item = cst; - for (const [field, index] of path5) { + for (const [field, index] of path6) { const tok = item?.[field]; if (tok && "items" in tok) { item = tok.items[index]; @@ -5550,23 +5550,23 @@ var require_cst_visit = __commonJS({ } return item; }; - visit.parentCollection = (cst, path5) => { - const parent = visit.itemAtPath(cst, path5.slice(0, -1)); - const field = path5[path5.length - 1][0]; + visit.parentCollection = (cst, path6) => { + const parent = visit.itemAtPath(cst, path6.slice(0, -1)); + const field = path6[path6.length - 1][0]; const coll = parent?.[field]; if (coll && "items" in coll) return coll; throw new Error("Parent collection not found"); }; - function _visit(path5, item, visitor) { - let ctrl = visitor(item, path5); + function _visit(path6, item, visitor) { + let ctrl = visitor(item, path6); if (typeof ctrl === "symbol") return ctrl; for (const field of ["key", "value"]) { const token = item[field]; if (token && "items" in token) { for (let i = 0; i < token.items.length; ++i) { - const ci = _visit(Object.freeze(path5.concat([[field, i]])), token.items[i], visitor); + const ci = _visit(Object.freeze(path6.concat([[field, i]])), token.items[i], visitor); if (typeof ci === "number") i = ci - 1; else if (ci === BREAK) @@ -5577,10 +5577,10 @@ var require_cst_visit = __commonJS({ } } if (typeof ctrl === "function" && field === "key") - ctrl = ctrl(item, path5); + ctrl = ctrl(item, path6); } } - return typeof ctrl === "function" ? ctrl(item, path5) : ctrl; + return typeof ctrl === "function" ? ctrl(item, path6) : ctrl; } exports2.visit = visit; } @@ -7233,7 +7233,7 @@ var require_public_api = __commonJS({ } return doc.toJS(Object.assign({ reviver: _reviver }, options)); } - function stringify(value, replacer, options) { + function stringify2(value, replacer, options) { let _replacer = null; if (typeof replacer === "function" || Array.isArray(replacer)) { _replacer = replacer; @@ -7258,7 +7258,7 @@ var require_public_api = __commonJS({ exports2.parse = parse; exports2.parseAllDocuments = parseAllDocuments; exports2.parseDocument = parseDocument; - exports2.stringify = stringify; + exports2.stringify = stringify2; } }); @@ -7429,6 +7429,1899 @@ function logging() { return cachedLogging; } +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/tslib.mjs +function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") + throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; +} +function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/uuid.mjs +var uuid4 = function() { + const { crypto: crypto2 } = globalThis; + if (crypto2?.randomUUID) { + uuid4 = crypto2.randomUUID.bind(crypto2); + return crypto2.randomUUID(); + } + const u8 = new Uint8Array(1); + const randomByte = crypto2 ? () => crypto2.getRandomValues(u8)[0] : () => Math.random() * 255 & 255; + return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16)); +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/errors.mjs +function isAbortError(err) { + return typeof err === "object" && err !== null && // Spec-compliant fetch implementations + ("name" in err && err.name === "AbortError" || // Expo fetch + "message" in err && String(err.message).includes("FetchRequestCanceledException")); +} +var castToError = (err) => { + if (err instanceof Error) + return err; + if (typeof err === "object" && err !== null) { + try { + if (Object.prototype.toString.call(err) === "[object Error]") { + const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); + if (err.stack) + error.stack = err.stack; + if (err.cause && !error.cause) + error.cause = err.cause; + if (err.name) + error.name = err.name; + return error; + } + } catch { + } + try { + return new Error(JSON.stringify(err)); + } catch { + } + } + return new Error(err); +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/core/error.mjs +var StainlessError = class extends Error { +}; +var APIError = class _APIError extends StainlessError { + constructor(status, error, message, headers) { + super(`${_APIError.makeMessage(status, error, message)}`); + this.status = status; + this.headers = headers; + this.error = error; + } + static makeMessage(status, error, message) { + const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message; + if (status && msg) { + return `${status} ${msg}`; + } + if (status) { + return `${status} status code (no body)`; + } + if (msg) { + return msg; + } + return "(no status code or body)"; + } + static generate(status, errorResponse, message, headers) { + if (!status || !headers) { + return new APIConnectionError({ message, cause: castToError(errorResponse) }); + } + const error = errorResponse; + if (status === 400) { + return new BadRequestError(status, error, message, headers); + } + if (status === 401) { + return new AuthenticationError(status, error, message, headers); + } + if (status === 403) { + return new PermissionDeniedError(status, error, message, headers); + } + if (status === 404) { + return new NotFoundError(status, error, message, headers); + } + if (status === 409) { + return new ConflictError(status, error, message, headers); + } + if (status === 422) { + return new UnprocessableEntityError(status, error, message, headers); + } + if (status === 429) { + return new RateLimitError(status, error, message, headers); + } + if (status >= 500) { + return new InternalServerError(status, error, message, headers); + } + return new _APIError(status, error, message, headers); + } +}; +var APIUserAbortError = class extends APIError { + constructor({ message } = {}) { + super(void 0, void 0, message || "Request was aborted.", void 0); + } +}; +var APIConnectionError = class extends APIError { + constructor({ message, cause }) { + super(void 0, void 0, message || "Connection error.", void 0); + if (cause) + this.cause = cause; + } +}; +var APIConnectionTimeoutError = class extends APIConnectionError { + constructor({ message } = {}) { + super({ message: message ?? "Request timed out." }); + } +}; +var BadRequestError = class extends APIError { +}; +var AuthenticationError = class extends APIError { +}; +var PermissionDeniedError = class extends APIError { +}; +var NotFoundError = class extends APIError { +}; +var ConflictError = class extends APIError { +}; +var UnprocessableEntityError = class extends APIError { +}; +var RateLimitError = class extends APIError { +}; +var InternalServerError = class extends APIError { +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/values.mjs +var startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; +var isAbsoluteURL = (url) => { + return startsWithSchemeRegexp.test(url); +}; +var isArray = (val) => (isArray = Array.isArray, isArray(val)); +var isReadonlyArray = isArray; +function maybeObj(x) { + if (typeof x !== "object") { + return {}; + } + return x ?? {}; +} +function isEmptyObj(obj) { + if (!obj) + return true; + for (const _k in obj) + return false; + return true; +} +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +var validatePositiveInteger = (name, n) => { + if (typeof n !== "number" || !Number.isInteger(n)) { + throw new StainlessError(`${name} must be an integer`); + } + if (n < 0) { + throw new StainlessError(`${name} must be a positive integer`); + } + return n; +}; +var safeJSON = (text) => { + try { + return JSON.parse(text); + } catch (err) { + return void 0; + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/sleep.mjs +var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/version.mjs +var VERSION = "0.5.0"; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/detect-platform.mjs +function getDetectedPlatform() { + if (typeof Deno !== "undefined" && Deno.build != null) { + return "deno"; + } + if (typeof EdgeRuntime !== "undefined") { + return "edge"; + } + if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") { + return "node"; + } + return "unknown"; +} +var getPlatformProperties = () => { + const detectedPlatform = getDetectedPlatform(); + if (detectedPlatform === "deno") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": normalizePlatform(Deno.build.os), + "X-Stainless-Arch": normalizeArch(Deno.build.arch), + "X-Stainless-Runtime": "deno", + "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown" + }; + } + if (typeof EdgeRuntime !== "undefined") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": `other:${EdgeRuntime}`, + "X-Stainless-Runtime": "edge", + "X-Stainless-Runtime-Version": globalThis.process.version + }; + } + if (detectedPlatform === "node") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": normalizePlatform(globalThis.process.platform ?? "unknown"), + "X-Stainless-Arch": normalizeArch(globalThis.process.arch ?? "unknown"), + "X-Stainless-Runtime": "node", + "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown" + }; + } + const browserInfo = getBrowserInfo(); + if (browserInfo) { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": "unknown", + "X-Stainless-Runtime": `browser:${browserInfo.browser}`, + "X-Stainless-Runtime-Version": browserInfo.version + }; + } + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": "unknown", + "X-Stainless-Runtime": "unknown", + "X-Stainless-Runtime-Version": "unknown" + }; +}; +function getBrowserInfo() { + if (typeof navigator === "undefined" || !navigator) { + return null; + } + const browserPatterns = [ + { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ } + ]; + for (const { key, pattern } of browserPatterns) { + const match2 = pattern.exec(navigator.userAgent); + if (match2) { + const major = match2[1] || 0; + const minor = match2[2] || 0; + const patch = match2[3] || 0; + return { browser: key, version: `${major}.${minor}.${patch}` }; + } + } + return null; +} +var normalizeArch = (arch) => { + if (arch === "x32") + return "x32"; + if (arch === "x86_64" || arch === "x64") + return "x64"; + if (arch === "arm") + return "arm"; + if (arch === "aarch64" || arch === "arm64") + return "arm64"; + if (arch) + return `other:${arch}`; + return "unknown"; +}; +var normalizePlatform = (platform) => { + platform = platform.toLowerCase(); + if (platform.includes("ios")) + return "iOS"; + if (platform === "android") + return "Android"; + if (platform === "darwin") + return "MacOS"; + if (platform === "win32") + return "Windows"; + if (platform === "freebsd") + return "FreeBSD"; + if (platform === "openbsd") + return "OpenBSD"; + if (platform === "linux") + return "Linux"; + if (platform) + return `Other:${platform}`; + return "Unknown"; +}; +var _platformHeaders; +var getPlatformHeaders = () => { + return _platformHeaders ?? (_platformHeaders = getPlatformProperties()); +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/shims.mjs +function getDefaultFetch() { + if (typeof fetch !== "undefined") { + return fetch; + } + throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Stainless({ fetch })` or polyfill the global, `globalThis.fetch = fetch`"); +} +function makeReadableStream(...args) { + const ReadableStream = globalThis.ReadableStream; + if (typeof ReadableStream === "undefined") { + throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`"); + } + return new ReadableStream(...args); +} +function ReadableStreamFrom(iterable) { + let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); + return makeReadableStream({ + start() { + }, + async pull(controller) { + const { done, value } = await iter.next(); + if (done) { + controller.close(); + } else { + controller.enqueue(value); + } + }, + async cancel() { + await iter.return?.(); + } + }); +} +async function CancelReadableStream(stream2) { + if (stream2 === null || typeof stream2 !== "object") + return; + if (stream2[Symbol.asyncIterator]) { + await stream2[Symbol.asyncIterator]().return?.(); + return; + } + const reader = stream2.getReader(); + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/request-options.mjs +var FallbackEncoder = ({ headers, body }) => { + return { + bodyHeaders: { + "content-type": "application/json" + }, + body: JSON.stringify(body) + }; +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/qs/formats.mjs +var default_format = "RFC3986"; +var default_formatter = (v) => String(v); +var formatters = { + RFC1738: (v) => String(v).replace(/%20/g, "+"), + RFC3986: default_formatter +}; +var RFC1738 = "RFC1738"; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/qs/utils.mjs +var has = (obj, key) => (has = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has(obj, key)); +var hex_table = /* @__PURE__ */ (() => { + const array = []; + for (let i = 0; i < 256; ++i) { + array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase()); + } + return array; +})(); +var limit = 1024; +var encode = (str, _defaultEncoder, charset, _kind, format) => { + if (str.length === 0) { + return str; + } + let string = str; + if (typeof str === "symbol") { + string = Symbol.prototype.toString.call(str); + } else if (typeof str !== "string") { + string = String(str); + } + if (charset === "iso-8859-1") { + return escape(string).replace(/%u[0-9a-f]{4}/gi, function($0) { + return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; + }); + } + let out = ""; + for (let j = 0; j < string.length; j += limit) { + const segment = string.length >= limit ? string.slice(j, j + limit) : string; + const arr = []; + for (let i = 0; i < segment.length; ++i) { + let c = segment.charCodeAt(i); + if (c === 45 || // - + c === 46 || // . + c === 95 || // _ + c === 126 || // ~ + c >= 48 && c <= 57 || // 0-9 + c >= 65 && c <= 90 || // a-z + c >= 97 && c <= 122 || // A-Z + format === RFC1738 && (c === 40 || c === 41)) { + arr[arr.length] = segment.charAt(i); + continue; + } + if (c < 128) { + arr[arr.length] = hex_table[c]; + continue; + } + if (c < 2048) { + arr[arr.length] = hex_table[192 | c >> 6] + hex_table[128 | c & 63]; + continue; + } + if (c < 55296 || c >= 57344) { + arr[arr.length] = hex_table[224 | c >> 12] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63]; + continue; + } + i += 1; + c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023); + arr[arr.length] = hex_table[240 | c >> 18] + hex_table[128 | c >> 12 & 63] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63]; + } + out += arr.join(""); + } + return out; +}; +function is_buffer(obj) { + if (!obj || typeof obj !== "object") { + return false; + } + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +} +function maybe_map(val, fn) { + if (isArray(val)) { + const mapped = []; + for (let i = 0; i < val.length; i += 1) { + mapped.push(fn(val[i])); + } + return mapped; + } + return fn(val); +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/qs/stringify.mjs +var array_prefix_generators = { + brackets(prefix) { + return String(prefix) + "[]"; + }, + comma: "comma", + indices(prefix, key) { + return String(prefix) + "[" + key + "]"; + }, + repeat(prefix) { + return String(prefix); + } +}; +var push_to_array = function(arr, value_or_array) { + Array.prototype.push.apply(arr, isArray(value_or_array) ? value_or_array : [value_or_array]); +}; +var toISOString; +var defaults = { + addQueryPrefix: false, + allowDots: false, + allowEmptyArrays: false, + arrayFormat: "indices", + charset: "utf-8", + charsetSentinel: false, + delimiter: "&", + encode: true, + encodeDotInKeys: false, + encoder: encode, + encodeValuesOnly: false, + format: default_format, + formatter: default_formatter, + /** @deprecated */ + indices: false, + serializeDate(date) { + return (toISOString ?? (toISOString = Function.prototype.call.bind(Date.prototype.toISOString)))(date); + }, + skipNulls: false, + strictNullHandling: false +}; +function is_non_nullish_primitive(v) { + return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint"; +} +var sentinel = {}; +function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter2, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { + let obj = object; + let tmp_sc = sideChannel; + let step = 0; + let find_flag = false; + while ((tmp_sc = tmp_sc.get(sentinel)) !== void 0 && !find_flag) { + const pos = tmp_sc.get(object); + step += 1; + if (typeof pos !== "undefined") { + if (pos === step) { + throw new RangeError("Cyclic object value"); + } else { + find_flag = true; + } + } + if (typeof tmp_sc.get(sentinel) === "undefined") { + step = 0; + } + } + if (typeof filter2 === "function") { + obj = filter2(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate?.(obj); + } else if (generateArrayPrefix === "comma" && isArray(obj)) { + obj = maybe_map(obj, function(value) { + if (value instanceof Date) { + return serializeDate?.(value); + } + return value; + }); + } + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? ( + // @ts-expect-error + encoder(prefix, defaults.encoder, charset, "key", format) + ) : prefix; + } + obj = ""; + } + if (is_non_nullish_primitive(obj) || is_buffer(obj)) { + if (encoder) { + const key_value = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, "key", format); + return [ + formatter?.(key_value) + "=" + // @ts-expect-error + formatter?.(encoder(obj, defaults.encoder, charset, "value", format)) + ]; + } + return [formatter?.(prefix) + "=" + formatter?.(String(obj))]; + } + const values = []; + if (typeof obj === "undefined") { + return values; + } + let obj_keys; + if (generateArrayPrefix === "comma" && isArray(obj)) { + if (encodeValuesOnly && encoder) { + obj = maybe_map(obj, encoder); + } + obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; + } else if (isArray(filter2)) { + obj_keys = filter2; + } else { + const keys = Object.keys(obj); + obj_keys = sort ? keys.sort(sort) : keys; + } + const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix); + const adjusted_prefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix; + if (allowEmptyArrays && isArray(obj) && obj.length === 0) { + return adjusted_prefix + "[]"; + } + for (let j = 0; j < obj_keys.length; ++j) { + const key = obj_keys[j]; + const value = ( + // @ts-ignore + typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key] + ); + if (skipNulls && value === null) { + continue; + } + const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key; + const key_prefix = isArray(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]"); + sideChannel.set(object, step); + const valueSideChannel = /* @__PURE__ */ new WeakMap(); + valueSideChannel.set(sentinel, sideChannel); + push_to_array(values, inner_stringify( + value, + key_prefix, + generateArrayPrefix, + commaRoundTrip, + allowEmptyArrays, + strictNullHandling, + skipNulls, + encodeDotInKeys, + // @ts-ignore + generateArrayPrefix === "comma" && encodeValuesOnly && isArray(obj) ? null : encoder, + filter2, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + valueSideChannel + )); + } + return values; +} +function normalize_stringify_options(opts = defaults) { + if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") { + throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); + } + if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") { + throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided"); + } + if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") { + throw new TypeError("Encoder has to be a function."); + } + const charset = opts.charset || defaults.charset; + if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { + throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); + } + let format = default_format; + if (typeof opts.format !== "undefined") { + if (!has(formatters, opts.format)) { + throw new TypeError("Unknown format option provided."); + } + format = opts.format; + } + const formatter = formatters[format]; + let filter2 = defaults.filter; + if (typeof opts.filter === "function" || isArray(opts.filter)) { + filter2 = opts.filter; + } + let arrayFormat; + if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) { + arrayFormat = opts.arrayFormat; + } else if ("indices" in opts) { + arrayFormat = opts.indices ? "indices" : "repeat"; + } else { + arrayFormat = defaults.arrayFormat; + } + if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") { + throw new TypeError("`commaRoundTrip` must be a boolean, or absent"); + } + const allowDots = typeof opts.allowDots === "undefined" ? !!opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; + return { + addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix, + // @ts-ignore + allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, + arrayFormat, + charset, + charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel, + commaRoundTrip: !!opts.commaRoundTrip, + delimiter: typeof opts.delimiter === "undefined" ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === "boolean" ? opts.encode : defaults.encode, + encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults.encodeDotInKeys, + encoder: typeof opts.encoder === "function" ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter: filter2, + format, + formatter, + serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults.skipNulls, + // @ts-ignore + sort: typeof opts.sort === "function" ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling + }; +} +function stringify(object, opts = {}) { + let obj = object; + const options = normalize_stringify_options(opts); + let obj_keys; + let filter2; + if (typeof options.filter === "function") { + filter2 = options.filter; + obj = filter2("", obj); + } else if (isArray(options.filter)) { + filter2 = options.filter; + obj_keys = filter2; + } + const keys = []; + if (typeof obj !== "object" || obj === null) { + return ""; + } + const generateArrayPrefix = array_prefix_generators[options.arrayFormat]; + const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip; + if (!obj_keys) { + obj_keys = Object.keys(obj); + } + if (options.sort) { + obj_keys.sort(options.sort); + } + const sideChannel = /* @__PURE__ */ new WeakMap(); + for (let i = 0; i < obj_keys.length; ++i) { + const key = obj_keys[i]; + if (options.skipNulls && obj[key] === null) { + continue; + } + push_to_array(keys, inner_stringify( + obj[key], + key, + // @ts-expect-error + generateArrayPrefix, + commaRoundTrip, + options.allowEmptyArrays, + options.strictNullHandling, + options.skipNulls, + options.encodeDotInKeys, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.format, + options.formatter, + options.encodeValuesOnly, + options.charset, + sideChannel + )); + } + const joined = keys.join(options.delimiter); + let prefix = options.addQueryPrefix === true ? "?" : ""; + if (options.charsetSentinel) { + if (options.charset === "iso-8859-1") { + prefix += "utf8=%26%2310003%3B&"; + } else { + prefix += "utf8=%E2%9C%93&"; + } + } + return joined.length > 0 ? prefix + joined : ""; +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/query.mjs +function stringifyQuery(query) { + return stringify(query, { arrayFormat: "comma" }); +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/log.mjs +var levelNumbers = { + off: 0, + error: 200, + warn: 300, + info: 400, + debug: 500 +}; +var parseLogLevel = (maybeLevel, sourceName, client) => { + if (!maybeLevel) { + return void 0; + } + if (hasOwn(levelNumbers, maybeLevel)) { + return maybeLevel; + } + loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`); + return void 0; +}; +function noop() { +} +function makeLogFn(fnLevel, logger2, logLevel) { + if (!logger2 || levelNumbers[fnLevel] > levelNumbers[logLevel]) { + return noop; + } else { + return logger2[fnLevel].bind(logger2); + } +} +var noopLogger = { + error: noop, + warn: noop, + info: noop, + debug: noop +}; +var cachedLoggers = /* @__PURE__ */ new WeakMap(); +function loggerFor(client) { + const logger2 = client.logger; + const logLevel = client.logLevel ?? "off"; + if (!logger2) { + return noopLogger; + } + const cachedLogger = cachedLoggers.get(logger2); + if (cachedLogger && cachedLogger[0] === logLevel) { + return cachedLogger[1]; + } + const levelLogger = { + error: makeLogFn("error", logger2, logLevel), + warn: makeLogFn("warn", logger2, logLevel), + info: makeLogFn("info", logger2, logLevel), + debug: makeLogFn("debug", logger2, logLevel) + }; + cachedLoggers.set(logger2, [logLevel, levelLogger]); + return levelLogger; +} +var formatRequestDetails = (details) => { + if (details.options) { + details.options = { ...details.options }; + delete details.options["headers"]; + } + if (details.headers) { + details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ + name, + name.toLowerCase() === "authorization" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value + ])); + } + if ("retryOfRequestLogID" in details) { + if (details.retryOfRequestLogID) { + details.retryOf = details.retryOfRequestLogID; + } + delete details.retryOfRequestLogID; + } + return details; +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/parse.mjs +async function defaultParseResponse(client, props) { + const { response, requestLogID, retryOfRequestLogID, startTime } = props; + const body = await (async () => { + if (response.status === 204) { + return null; + } + if (props.options.__binaryResponse) { + return response; + } + const contentType = response.headers.get("content-type"); + const mediaType = contentType?.split(";")[0]?.trim(); + const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json"); + if (isJSON) { + const contentLength = response.headers.get("content-length"); + if (contentLength === "0") { + return void 0; + } + const json = await response.json(); + return json; + } + const text = await response.text(); + return text; + })(); + loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + body, + durationMs: Date.now() - startTime + })); + return body; +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/core/api-promise.mjs +var _APIPromise_client; +var APIPromise = class _APIPromise extends Promise { + constructor(client, responsePromise, parseResponse = defaultParseResponse) { + super((resolve) => { + resolve(null); + }); + this.responsePromise = responsePromise; + this.parseResponse = parseResponse; + _APIPromise_client.set(this, void 0); + __classPrivateFieldSet(this, _APIPromise_client, client, "f"); + } + _thenUnwrap(transform) { + return new _APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => transform(await this.parseResponse(client, props), props)); + } + /** + * Gets the raw `Response` instance instead of parsing the response + * data. + * + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + asResponse() { + return this.responsePromise.then((p) => p.response); + } + /** + * Gets the parsed response data and the raw `Response` instance. + * + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + async withResponse() { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { data, response }; + } + parse() { + if (!this.parsedPromise) { + this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data)); + } + return this.parsedPromise; + } + then(onfulfilled, onrejected) { + return this.parse().then(onfulfilled, onrejected); + } + catch(onrejected) { + return this.parse().catch(onrejected); + } + finally(onfinally) { + return this.parse().finally(onfinally); + } +}; +_APIPromise_client = /* @__PURE__ */ new WeakMap(); + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/core/pagination.mjs +var _AbstractPage_client; +var AbstractPage = class { + constructor(client, response, body, options) { + _AbstractPage_client.set(this, void 0); + __classPrivateFieldSet(this, _AbstractPage_client, client, "f"); + this.options = options; + this.response = response; + this.body = body; + } + hasNextPage() { + const items = this.getPaginatedItems(); + if (!items.length) + return false; + return this.nextPageRequestOptions() != null; + } + async getNextPage() { + const nextOptions = this.nextPageRequestOptions(); + if (!nextOptions) { + throw new StainlessError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`."); + } + return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); + } + async *iterPages() { + let page = this; + yield page; + while (page.hasNextPage()) { + page = await page.getNextPage(); + yield page; + } + } + async *[(_AbstractPage_client = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() { + for await (const page of this.iterPages()) { + for (const item of page.getPaginatedItems()) { + yield item; + } + } + } +}; +var PagePromise = class extends APIPromise { + constructor(client, request, Page2) { + super(client, request, async (client2, props) => new Page2(client2, props.response, await defaultParseResponse(client2, props), props.options)); + } + /** + * Allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ + async *[Symbol.asyncIterator]() { + const page = await this; + for await (const item of page) { + yield item; + } + } +}; +var Page = class extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.next_cursor = body.next_cursor || ""; + } + getPaginatedItems() { + return this.data ?? []; + } + nextPageRequestOptions() { + const cursor = this.next_cursor; + if (!cursor) { + return null; + } + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + cursor + } + }; + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/uploads.mjs +var checkFileSupport = () => { + if (typeof File === "undefined") { + const { process: process7 } = globalThis; + const isOldNode = typeof process7?.versions?.node === "string" && parseInt(process7.versions.node.split(".")) < 20; + throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : "")); + } +}; +function makeFile(fileBits, fileName, options) { + checkFileSupport(); + return new File(fileBits, fileName ?? "unknown_file", options); +} +function getName(value) { + return (typeof value === "object" && value !== null && ("name" in value && value.name && String(value.name) || "url" in value && value.url && String(value.url) || "filename" in value && value.filename && String(value.filename) || "path" in value && value.path && String(value.path)) || "").split(/[\\/]/).pop() || void 0; +} +var isAsyncIterable = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function"; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/to-file.mjs +var isBlobLike = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function"; +var isFileLike = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value); +var isResponseLike = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function"; +async function toFile(value, name, options) { + checkFileSupport(); + value = await value; + if (isFileLike(value)) { + if (value instanceof File) { + return value; + } + return makeFile([await value.arrayBuffer()], value.name); + } + if (isResponseLike(value)) { + const blob = await value.blob(); + name || (name = new URL(value.url).pathname.split(/[\\/]/).pop()); + return makeFile(await getBytes(blob), name, options); + } + const parts = await getBytes(value); + name || (name = getName(value)); + if (!options?.type) { + const type = parts.find((part) => typeof part === "object" && "type" in part && part.type); + if (typeof type === "string") { + options = { ...options, type }; + } + } + return makeFile(parts, name, options); +} +async function getBytes(value) { + let parts = []; + if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. + value instanceof ArrayBuffer) { + parts.push(value); + } else if (isBlobLike(value)) { + parts.push(value instanceof Blob ? value : await value.arrayBuffer()); + } else if (isAsyncIterable(value)) { + for await (const chunk of value) { + parts.push(...await getBytes(chunk)); + } + } else { + const constructor = value?.constructor?.name; + throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError(value)}`); + } + return parts; +} +function propsForError(value) { + if (typeof value !== "object" || value === null) + return ""; + const props = Object.getOwnPropertyNames(value); + return `; props: [${props.map((p) => `"${p}"`).join(", ")}]`; +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/core/resource.mjs +var APIResource = class { + constructor(client) { + this._client = client; + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/path.mjs +function encodeURIPath(str) { + return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); +} +var EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); +var createPathTagFunction = (pathEncoder = encodeURIPath) => function path6(statics, ...params) { + if (statics.length === 1) + return statics[0]; + let postPath = false; + const invalidSegments = []; + const path7 = statics.reduce((previousValue, currentValue, index) => { + if (/[?#]/.test(currentValue)) { + postPath = true; + } + const value = params[index]; + let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value); + if (index !== params.length && (value == null || typeof value === "object" && // handle values from other realms + value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY)?.toString)) { + encoded = value + ""; + invalidSegments.push({ + start: previousValue.length + currentValue.length, + length: encoded.length, + error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter` + }); + } + return previousValue + currentValue + (index === params.length ? "" : encoded); + }, ""); + const pathOnly = path7.split(/[?#]/, 1)[0]; + const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; + let match2; + while ((match2 = invalidSegmentPattern.exec(pathOnly)) !== null) { + invalidSegments.push({ + start: match2.index, + length: match2[0].length, + error: `Value "${match2[0]}" can't be safely passed as a path parameter` + }); + } + invalidSegments.sort((a, b) => a.start - b.start); + if (invalidSegments.length > 0) { + let lastEnd = 0; + const underline = invalidSegments.reduce((acc, segment) => { + const spaces = " ".repeat(segment.start - lastEnd); + const arrows = "^".repeat(segment.length); + lastEnd = segment.start + segment.length; + return acc + spaces + arrows; + }, ""); + throw new StainlessError(`Path parameters result in path with invalid segments: +${invalidSegments.map((e) => e.error).join("\n")} +${path7} +${underline}`); + } + return path7; +}; +var path = /* @__PURE__ */ createPathTagFunction(encodeURIPath); + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/builds/diagnostics.mjs +var Diagnostics = class extends APIResource { + /** + * Get the list of diagnostics for a given build. + * + * If no language targets are specified, diagnostics for all languages are + * returned. + */ + list(buildID, query = {}, options) { + return this._client.getAPIList(path`/v0/builds/${buildID}/diagnostics`, Page, { + query, + ...options + }); + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/builds/target-outputs.mjs +var TargetOutputs = class extends APIResource { + /** + * Retrieve a method to download an output for a given build target. + * + * If the requested type of output is `source`, and the requested output method is + * `url`, a download link to a tarball of the source files is returned. If the + * requested output method is `git`, a Git remote, ref, and access token (if + * necessary) is returned. + * + * Otherwise, the possible types of outputs are specific to the requested target, + * and the output method _must_ be `url`. See the documentation for `type` for more + * information. + */ + retrieve(query, options) { + return this._client.get("/v0/build_target_outputs", { query, ...options }); + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/builds/builds.mjs +var Builds = class extends APIResource { + constructor() { + super(...arguments); + this.diagnostics = new Diagnostics(this._client); + this.targetOutputs = new TargetOutputs(this._client); + } + /** + * Create a build, on top of a project branch, against a given input revision. + * + * The project branch will be modified so that its latest set of config files + * points to the one specified by the input revision. + */ + create(params, options) { + const { project = this._client.project, ...body } = params; + return this._client.post("/v0/builds", { body: { project, ...body }, ...options }); + } + /** + * Retrieve a build by its ID. + */ + retrieve(buildID, options) { + return this._client.get(path`/v0/builds/${buildID}`, options); + } + /** + * List user-triggered builds for a given project. + * + * An optional revision can be specified to filter by config commit SHA, or hashes + * of file contents. + */ + list(params = {}, options) { + const { project = this._client.project, ...query } = params ?? {}; + return this._client.getAPIList("/v0/builds", Page, { query: { project, ...query }, ...options }); + } + /** + * Create two builds whose outputs can be directly compared with each other. + * + * Created builds _modify_ their project branches so that their latest sets of + * config files point to the ones specified by the input revision. + * + * This endpoint is useful because a build has more inputs than the set of config + * files it uses, so comparing two builds directly may return spurious differences. + * Builds made via this endpoint are guaranteed to have differences arising from + * the set of config files, and any custom code. + */ + compare(params, options) { + const { project = this._client.project, ...body } = params; + return this._client.post("/v0/builds/compare", { body: { project, ...body }, ...options }); + } +}; +Builds.Diagnostics = Diagnostics; +Builds.TargetOutputs = TargetOutputs; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/orgs.mjs +var Orgs = class extends APIResource { + /** + * Retrieve an organization by name. + */ + retrieve(org, options) { + return this._client.get(path`/v0/orgs/${org}`, options); + } + /** + * List organizations accessible to the current authentication method. + */ + list(options) { + return this._client.get("/v0/orgs", options); + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/projects/branches.mjs +var Branches = class extends APIResource { + /** + * Create a new branch for a project. + * + * The branch inherits the config files from the revision pointed to by the + * `branch_from` parameter. In addition, if the revision is a branch name, the + * branch will also inherit custom code changes from that branch. + */ + create(params, options) { + const { project = this._client.project, ...body } = params; + return this._client.post(path`/v0/projects/${project}/branches`, { body, ...options }); + } + /** + * Retrieve a project branch by name. + */ + retrieve(branch, params = {}, options) { + const { project = this._client.project } = params ?? {}; + return this._client.get(path`/v0/projects/${project}/branches/${branch}`, options); + } + /** + * Retrieve a project branch by name. + */ + list(params = {}, options) { + const { project = this._client.project, ...query } = params ?? {}; + return this._client.getAPIList(path`/v0/projects/${project}/branches`, Page, { + query, + ...options + }); + } + /** + * Delete a project branch by name. + */ + delete(branch, params = {}, options) { + const { project = this._client.project } = params ?? {}; + return this._client.delete(path`/v0/projects/${project}/branches/${branch}`, options); + } + /** + * Rebase a project branch. + * + * The branch is rebased onto the `base` branch or commit SHA, inheriting any + * config and custom code changes. + */ + rebase(branch, params = {}, options) { + const { project = this._client.project, base } = params ?? {}; + return this._client.put(path`/v0/projects/${project}/branches/${branch}/rebase`, { + query: { base }, + ...options + }); + } + /** + * Reset a project branch. + * + * If `branch` === `main`, the branch is reset to `target_config_sha`. Otherwise, + * the branch is reset to `main`. + */ + reset(branch, params = {}, options) { + const { project = this._client.project, target_config_sha } = params ?? {}; + return this._client.put(path`/v0/projects/${project}/branches/${branch}/reset`, { + query: { target_config_sha }, + ...options + }); + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/projects/configs.mjs +var Configs = class extends APIResource { + /** + * Retrieve the configuration files for a given project. + */ + retrieve(params = {}, options) { + const { project = this._client.project, ...query } = params ?? {}; + return this._client.get(path`/v0/projects/${project}/configs`, { query, ...options }); + } + /** + * Generate suggestions for changes to config files based on an OpenAPI spec. + */ + guess(params, options) { + const { project = this._client.project, ...body } = params; + return this._client.post(path`/v0/projects/${project}/configs/guess`, { body, ...options }); + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/projects/projects.mjs +var Projects = class extends APIResource { + constructor() { + super(...arguments); + this.branches = new Branches(this._client); + this.configs = new Configs(this._client); + } + /** + * Create a new project. + */ + create(body, options) { + return this._client.post("/v0/projects", { body, ...options }); + } + /** + * Retrieve a project by name. + */ + retrieve(params = {}, options) { + const { project = this._client.project } = params ?? {}; + return this._client.get(path`/v0/projects/${project}`, options); + } + /** + * Update a project's properties. + */ + update(params = {}, options) { + const { project = this._client.project, ...body } = params ?? {}; + return this._client.patch(path`/v0/projects/${project}`, { body, ...options }); + } + /** + * List projects in an organization, from oldest to newest. + */ + list(query = {}, options) { + return this._client.getAPIList("/v0/projects", Page, { query, ...options }); + } + /** + * Generates an AI commit message by comparing two git refs in the SDK repository. + */ + generateCommitMessage(params, options) { + const { project = this._client.project, target, ...body } = params; + return this._client.post(path`/v0/projects/${project}/generate_commit_message`, { + query: { target }, + body, + ...options + }); + } +}; +Projects.Branches = Branches; +Projects.Configs = Configs; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/user.mjs +var User = class extends APIResource { + /** + * Retrieve the currently authenticated user's information. + */ + retrieve(options) { + return this._client.get("/v0/user", options); + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/headers.mjs +var brand_privateNullableHeaders = /* @__PURE__ */ Symbol("brand.privateNullableHeaders"); +function* iterateHeaders(headers) { + if (!headers) + return; + if (brand_privateNullableHeaders in headers) { + const { values, nulls } = headers; + yield* values.entries(); + for (const name of nulls) { + yield [name, null]; + } + return; + } + let shouldClear = false; + let iter; + if (headers instanceof Headers) { + iter = headers.entries(); + } else if (isReadonlyArray(headers)) { + iter = headers; + } else { + shouldClear = true; + iter = Object.entries(headers ?? {}); + } + for (let row of iter) { + const name = row[0]; + if (typeof name !== "string") + throw new TypeError("expected header name to be a string"); + const values = isReadonlyArray(row[1]) ? row[1] : [row[1]]; + let didClear = false; + for (const value of values) { + if (value === void 0) + continue; + if (shouldClear && !didClear) { + didClear = true; + yield [name, null]; + } + yield [name, value]; + } + } +} +var buildHeaders = (newHeaders) => { + const targetHeaders = new Headers(); + const nullHeaders = /* @__PURE__ */ new Set(); + for (const headers of newHeaders) { + const seenHeaders = /* @__PURE__ */ new Set(); + for (const [name, value] of iterateHeaders(headers)) { + const lowerName = name.toLowerCase(); + if (!seenHeaders.has(lowerName)) { + targetHeaders.delete(name); + seenHeaders.add(lowerName); + } + if (value === null) { + targetHeaders.delete(name); + nullHeaders.add(lowerName); + } else { + targetHeaders.append(name, value); + nullHeaders.delete(lowerName); + } + } + } + return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders }; +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/env.mjs +var readEnv = (env) => { + if (typeof globalThis.process !== "undefined") { + return globalThis.process.env?.[env]?.trim() ?? void 0; + } + if (typeof globalThis.Deno !== "undefined") { + return globalThis.Deno.env?.get?.(env)?.trim(); + } + return void 0; +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/lib/unwrap.mjs +async function unwrapFile(value) { + if (value === null) { + return null; + } + if (value.type === "content") { + return value.content; + } + const response = await fetch(value.url); + return response.text(); +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/client.mjs +var _Stainless_instances; +var _a; +var _Stainless_encoder; +var _Stainless_baseURLOverridden; +var environments = { + production: "https://api.stainless.com", + staging: "https://staging.stainless.com" +}; +var Stainless = class { + /** + * API Client for interfacing with the Stainless API. + * + * @param {string | null | undefined} [opts.apiKey=process.env['STAINLESS_API_KEY'] ?? null] + * @param {string | null | undefined} [opts.project] + * @param {Environment} [opts.environment=production] - Specifies the environment URL to use for the API. + * @param {string} [opts.baseURL=process.env['STAINLESS_BASE_URL'] ?? https://api.stainless.com] - Override the default base URL for the API. + * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. + * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. + */ + constructor({ baseURL = readEnv("STAINLESS_BASE_URL"), apiKey = readEnv("STAINLESS_API_KEY") ?? null, project = null, ...opts } = {}) { + _Stainless_instances.add(this); + _Stainless_encoder.set(this, void 0); + this.projects = new Projects(this); + this.builds = new Builds(this); + this.orgs = new Orgs(this); + this.user = new User(this); + const options = { + apiKey, + project, + ...opts, + baseURL, + environment: opts.environment ?? "production" + }; + if (baseURL && opts.environment) { + throw new StainlessError("Ambiguous URL; The `baseURL` option (or STAINLESS_BASE_URL env var) and the `environment` option are given. If you want to use the environment you must pass baseURL: null"); + } + this.baseURL = options.baseURL || environments[options.environment || "production"]; + this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT; + this.logger = options.logger ?? console; + const defaultLogLevel = "warn"; + this.logLevel = defaultLogLevel; + this.logLevel = parseLogLevel(options.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel(readEnv("STAINLESS_LOG"), "process.env['STAINLESS_LOG']", this) ?? defaultLogLevel; + this.fetchOptions = options.fetchOptions; + this.maxRetries = options.maxRetries ?? 2; + this.fetch = options.fetch ?? getDefaultFetch(); + __classPrivateFieldSet(this, _Stainless_encoder, FallbackEncoder, "f"); + this._options = options; + this.apiKey = apiKey; + this.project = project; + } + /** + * Create a new client instance re-using the same options given to the current client with optional overriding. + */ + withOptions(options) { + const client = new this.constructor({ + ...this._options, + environment: options.environment ? options.environment : void 0, + baseURL: options.environment ? void 0 : this.baseURL, + maxRetries: this.maxRetries, + timeout: this.timeout, + logger: this.logger, + logLevel: this.logLevel, + fetch: this.fetch, + fetchOptions: this.fetchOptions, + apiKey: this.apiKey, + project: this.project, + ...options + }); + return client; + } + defaultQuery() { + return this._options.defaultQuery; + } + validateHeaders({ values, nulls }) { + if (this.apiKey && values.get("authorization")) { + return; + } + if (nulls.has("authorization")) { + return; + } + throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "Authorization" headers to be explicitly omitted'); + } + async authHeaders(opts) { + if (this.apiKey == null) { + return void 0; + } + return buildHeaders([{ Authorization: `Bearer ${this.apiKey}` }]); + } + stringifyQuery(query) { + return stringifyQuery(query); + } + getUserAgent() { + return `${this.constructor.name}/JS ${VERSION}`; + } + defaultIdempotencyKey() { + return `stainless-node-retry-${uuid4()}`; + } + makeStatusError(status, error, message, headers) { + return APIError.generate(status, error, message, headers); + } + buildURL(path6, query, defaultBaseURL) { + const baseURL = !__classPrivateFieldGet(this, _Stainless_instances, "m", _Stainless_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL; + const url = isAbsoluteURL(path6) ? new URL(path6) : new URL(baseURL + (baseURL.endsWith("/") && path6.startsWith("/") ? path6.slice(1) : path6)); + const defaultQuery = this.defaultQuery(); + if (!isEmptyObj(defaultQuery)) { + query = { ...defaultQuery, ...query }; + } + if (typeof query === "object" && query && !Array.isArray(query)) { + url.search = this.stringifyQuery(query); + } + return url.toString(); + } + /** + * Used as a callback for mutating the given `FinalRequestOptions` object. + */ + async prepareOptions(options) { + } + /** + * Used as a callback for mutating the given `RequestInit` object. + * + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. + */ + async prepareRequest(request, { url, options }) { + } + get(path6, opts) { + return this.methodRequest("get", path6, opts); + } + post(path6, opts) { + return this.methodRequest("post", path6, opts); + } + patch(path6, opts) { + return this.methodRequest("patch", path6, opts); + } + put(path6, opts) { + return this.methodRequest("put", path6, opts); + } + delete(path6, opts) { + return this.methodRequest("delete", path6, opts); + } + methodRequest(method, path6, opts) { + return this.request(Promise.resolve(opts).then((opts2) => { + return { method, path: path6, ...opts2 }; + })); + } + request(options, remainingRetries = null) { + return new APIPromise(this, this.makeRequest(options, remainingRetries, void 0)); + } + async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { + const options = await optionsInput; + const maxRetries = options.maxRetries ?? this.maxRetries; + if (retriesRemaining == null) { + retriesRemaining = maxRetries; + } + await this.prepareOptions(options); + const { req, url, timeout } = await this.buildRequest(options, { + retryCount: maxRetries - retriesRemaining + }); + await this.prepareRequest(req, { url, options }); + const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0"); + const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`; + const startTime = Date.now(); + loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({ + retryOfRequestLogID, + method: options.method, + url, + options, + headers: req.headers + })); + if (options.signal?.aborted) { + throw new APIUserAbortError(); + } + const controller = new AbortController(); + const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError); + const headersTime = Date.now(); + if (response instanceof globalThis.Error) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + if (options.signal?.aborted) { + throw new APIUserAbortError(); + } + const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : "")); + if (retriesRemaining) { + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`); + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); + } + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`); + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + if (isTimeout) { + throw new APIConnectionTimeoutError(); + } + throw new APIConnectionError({ cause: response }); + } + const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`; + if (!response.ok) { + const shouldRetry = await this.shouldRetry(response); + if (retriesRemaining && shouldRetry) { + const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`; + await CancelReadableStream(response.body); + loggerFor(this).info(`${responseInfo} - ${retryMessage2}`); + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); + } + const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; + loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + const errText = await response.text().catch((err2) => castToError(err2).message); + const errJSON = safeJSON(errText); + const errMessage = errJSON ? void 0 : errText; + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + message: errMessage, + durationMs: Date.now() - startTime + })); + const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); + throw err; + } + loggerFor(this).info(responseInfo); + loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; + } + getAPIList(path6, Page2, opts) { + return this.requestAPIList(Page2, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path6, ...opts2 })) : { method: "get", path: path6, ...opts }); + } + requestAPIList(Page2, options) { + const request = this.makeRequest(options, null, void 0); + return new PagePromise(this, request, Page2); + } + async fetchWithTimeout(url, init, ms, controller) { + const { signal, method, ...options } = init || {}; + const abort = this._makeAbort(controller); + if (signal) + signal.addEventListener("abort", abort, { once: true }); + const timeout = setTimeout(abort, ms); + const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body; + const fetchOptions = { + signal: controller.signal, + ...isReadableBody ? { duplex: "half" } : {}, + method: "GET", + ...options + }; + if (method) { + fetchOptions.method = method.toUpperCase(); + } + try { + return await this.fetch.call(void 0, url, fetchOptions); + } finally { + clearTimeout(timeout); + } + } + async shouldRetry(response) { + const shouldRetryHeader = response.headers.get("x-should-retry"); + if (shouldRetryHeader === "true") + return true; + if (shouldRetryHeader === "false") + return false; + if (response.status === 408) + return true; + if (response.status === 409) + return true; + if (response.status === 429) + return true; + if (response.status >= 500) + return true; + return false; + } + async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { + let timeoutMillis; + const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms"); + if (retryAfterMillisHeader) { + const timeoutMs = parseFloat(retryAfterMillisHeader); + if (!Number.isNaN(timeoutMs)) { + timeoutMillis = timeoutMs; + } + } + const retryAfterHeader = responseHeaders?.get("retry-after"); + if (retryAfterHeader && !timeoutMillis) { + const timeoutSeconds = parseFloat(retryAfterHeader); + if (!Number.isNaN(timeoutSeconds)) { + timeoutMillis = timeoutSeconds * 1e3; + } else { + timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); + } + } + if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1e3)) { + const maxRetries = options.maxRetries ?? this.maxRetries; + timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + } + await sleep(timeoutMillis); + return this.makeRequest(options, retriesRemaining - 1, requestLogID); + } + calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { + const initialRetryDelay = 0.5; + const maxRetryDelay = 8; + const numRetries = maxRetries - retriesRemaining; + const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); + const jitter = 1 - Math.random() * 0.25; + return sleepSeconds * jitter * 1e3; + } + async buildRequest(inputOptions, { retryCount = 0 } = {}) { + const options = { ...inputOptions }; + const { method, path: path6, query, defaultBaseURL } = options; + const url = this.buildURL(path6, query, defaultBaseURL); + if ("timeout" in options) + validatePositiveInteger("timeout", options.timeout); + options.timeout = options.timeout ?? this.timeout; + const { bodyHeaders, body } = this.buildBody({ options }); + const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); + const req = { + method, + headers: reqHeaders, + ...options.signal && { signal: options.signal }, + ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" }, + ...body && { body }, + ...this.fetchOptions ?? {}, + ...options.fetchOptions ?? {} + }; + return { req, url, timeout: options.timeout }; + } + async buildHeaders({ options, method, bodyHeaders, retryCount }) { + let idempotencyHeaders = {}; + if (this.idempotencyHeader && method !== "get") { + if (!options.idempotencyKey) + options.idempotencyKey = this.defaultIdempotencyKey(); + idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; + } + const headers = buildHeaders([ + idempotencyHeaders, + { + Accept: "application/json", + "User-Agent": this.getUserAgent(), + "X-Stainless-Retry-Count": String(retryCount), + ...options.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options.timeout / 1e3)) } : {}, + ...getPlatformHeaders() + }, + await this.authHeaders(options), + this._options.defaultHeaders, + bodyHeaders, + options.headers + ]); + this.validateHeaders(headers); + return headers.values; + } + _makeAbort(controller) { + return () => controller.abort(); + } + buildBody({ options: { body, headers: rawHeaders } }) { + if (!body) { + return { bodyHeaders: void 0, body: void 0 }; + } + const headers = buildHeaders([rawHeaders]); + if ( + // Pass raw type verbatim + ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && // Preserve legacy string encoding behavior for now + headers.values.has("content-type") || // `Blob` is superset of `File` + globalThis.Blob && body instanceof globalThis.Blob || // `FormData` -> `multipart/form-data` + body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded` + body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`) + globalThis.ReadableStream && body instanceof globalThis.ReadableStream + ) { + return { bodyHeaders: void 0, body }; + } else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) { + return { bodyHeaders: void 0, body: ReadableStreamFrom(body) }; + } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") { + return { + bodyHeaders: { "content-type": "application/x-www-form-urlencoded" }, + body: this.stringifyQuery(body) + }; + } else { + return __classPrivateFieldGet(this, _Stainless_encoder, "f").call(this, { body, headers }); + } + } +}; +_a = Stainless, _Stainless_encoder = /* @__PURE__ */ new WeakMap(), _Stainless_instances = /* @__PURE__ */ new WeakSet(), _Stainless_baseURLOverridden = function _Stainless_baseURLOverridden2() { + return this.baseURL !== environments[this._options.environment || "production"]; +}; +Stainless.Stainless = _a; +Stainless.DEFAULT_TIMEOUT = 6e4; +Stainless.StainlessError = StainlessError; +Stainless.APIError = APIError; +Stainless.APIConnectionError = APIConnectionError; +Stainless.APIConnectionTimeoutError = APIConnectionTimeoutError; +Stainless.APIUserAbortError = APIUserAbortError; +Stainless.NotFoundError = NotFoundError; +Stainless.ConflictError = ConflictError; +Stainless.RateLimitError = RateLimitError; +Stainless.BadRequestError = BadRequestError; +Stainless.AuthenticationError = AuthenticationError; +Stainless.InternalServerError = InternalServerError; +Stainless.PermissionDeniedError = PermissionDeniedError; +Stainless.UnprocessableEntityError = UnprocessableEntityError; +Stainless.toFile = toFile; +Stainless.unwrapFile = unwrapFile; +Stainless.Projects = Projects; +Stainless.Builds = Builds; +Stainless.Orgs = Orgs; +Stainless.User = User; + +// src/error.ts +var ActionError = class extends Error { + constructor(message, options) { + super(message, options); + this.name = "ActionError"; + } +}; + // src/logger.ts var LOG_LEVELS = { debug: 0, @@ -7513,11 +9406,14 @@ function createLoggerImpl(logContext) { error: errorFn, fatal(message, ...args) { errorFn(message, ...args); - process.stderr.write( - ` + const isActionError = args.some((arg) => arg instanceof ActionError); + if (!isActionError) { + process.stderr.write( + ` This is a bug. Please report it at ${BUG_REPORT_URL} ` - ); + ); + } }, child(childContext) { const { context, ...rest } = logContext; @@ -7559,7 +9455,7 @@ var logger = createLogger(); // src/combine/combine.ts var fs3 = __toESM(require("node:fs/promises")); -var path4 = __toESM(require("node:path")); +var path5 = __toESM(require("node:path")); // node_modules/.pnpm/@isaacs+balanced-match@4.0.1/node_modules/@isaacs/balanced-match/dist/esm/index.js var balanced = (a, b, str) => { @@ -7893,7 +9789,7 @@ var parseClass = (glob2, position) => { }; // node_modules/.pnpm/minimatch@10.1.1/node_modules/minimatch/dist/esm/unescape.js -var unescape = (s, { windowsPathsNoEscape = false, magicalBraces = true } = {}) => { +var unescape2 = (s, { windowsPathsNoEscape = false, magicalBraces = true } = {}) => { if (magicalBraces) { return windowsPathsNoEscape ? s.replace(/\[([^\/\\])\]/g, "$1") : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1"); } @@ -8282,7 +10178,7 @@ var AST = class _AST { const final2 = start2 + src + end; return [ final2, - unescape(src), + unescape2(src), this.#hasMagic = !!this.#hasMagic, this.#uflag ]; @@ -8295,7 +10191,7 @@ var AST = class _AST { this.#parts = [s]; this.type = null; this.#hasMagic = void 0; - return [s, unescape(this.toString()), false, false]; + return [s, unescape2(this.toString()), false, false]; } let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ? "" : this.#partsToRegExp(true); if (bodyDotAllowed === body) { @@ -8316,7 +10212,7 @@ var AST = class _AST { } return [ final, - unescape(body), + unescape2(body), this.#hasMagic = !!this.#hasMagic, this.#uflag ]; @@ -8372,12 +10268,12 @@ var AST = class _AST { } re += regExpEscape(c); } - return [re, unescape(glob2), !!hasMagic2, uflag]; + return [re, unescape2(glob2), !!hasMagic2, uflag]; } }; // node_modules/.pnpm/minimatch@10.1.1/node_modules/minimatch/dist/esm/escape.js -var escape = (s, { windowsPathsNoEscape = false, magicalBraces = false } = {}) => { +var escape2 = (s, { windowsPathsNoEscape = false, magicalBraces = false } = {}) => { if (magicalBraces) { return windowsPathsNoEscape ? s.replace(/[?*()[\]{}]/g, "[$&]") : s.replace(/[?*()[\]\\{}]/g, "\\$&"); } @@ -8443,11 +10339,11 @@ var qmarksTestNoExtDot = ([$0]) => { return (f) => f.length === len && f !== "." && f !== ".."; }; var defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix"; -var path = { +var path2 = { win32: { sep: "\\" }, posix: { sep: "/" } }; -var sep = defaultPlatform === "win32" ? path.win32.sep : path.posix.sep; +var sep = defaultPlatform === "win32" ? path2.win32.sep : path2.posix.sep; minimatch.sep = sep; var GLOBSTAR = Symbol("globstar **"); minimatch.GLOBSTAR = GLOBSTAR; @@ -8458,7 +10354,7 @@ var twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?"; var filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options); minimatch.filter = filter; var ext = (a, b = {}) => Object.assign({}, a, b); -var defaults = (def) => { +var defaults2 = (def) => { if (!def || typeof def !== "object" || !Object.keys(def).length) { return minimatch; } @@ -8494,7 +10390,7 @@ var defaults = (def) => { GLOBSTAR }); }; -minimatch.defaults = defaults; +minimatch.defaults = defaults2; var braceExpand = (pattern, options = {}) => { assertValidPattern(pattern); if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { @@ -9110,8 +11006,8 @@ var Minimatch = class { }; minimatch.AST = AST; minimatch.Minimatch = Minimatch; -minimatch.escape = escape; -minimatch.unescape = unescape; +minimatch.escape = escape2; +minimatch.unescape = unescape2; // node_modules/.pnpm/glob@11.1.0/node_modules/glob/dist/esm/glob.js var import_node_url2 = require("node:url"); @@ -11692,12 +13588,12 @@ var PathBase = class { /** * Get the Path object referenced by the string path, resolved from this Path */ - resolve(path5) { - if (!path5) { + resolve(path6) { + if (!path6) { return this; } - const rootPath = this.getRootString(path5); - const dir = path5.substring(rootPath.length); + const rootPath = this.getRootString(path6); + const dir = path6.substring(rootPath.length); const dirParts = dir.split(this.splitSep); const result = rootPath ? this.getRoot(rootPath).#resolveParts(dirParts) : this.#resolveParts(dirParts); return result; @@ -12449,8 +14345,8 @@ var PathWin32 = class _PathWin32 extends PathBase { /** * @internal */ - getRootString(path5) { - return import_node_path.win32.parse(path5).root; + getRootString(path6) { + return import_node_path.win32.parse(path6).root; } /** * @internal @@ -12496,8 +14392,8 @@ var PathPosix = class _PathPosix extends PathBase { /** * @internal */ - getRootString(path5) { - return path5.startsWith("/") ? "/" : ""; + getRootString(path6) { + return path6.startsWith("/") ? "/" : ""; } /** * @internal @@ -12586,11 +14482,11 @@ var PathScurryBase = class { /** * Get the depth of a provided path, string, or the cwd */ - depth(path5 = this.cwd) { - if (typeof path5 === "string") { - path5 = this.cwd.resolve(path5); + depth(path6 = this.cwd) { + if (typeof path6 === "string") { + path6 = this.cwd.resolve(path6); } - return path5.depth(); + return path6.depth(); } /** * Return the cache of child entries. Exposed so subclasses can create @@ -13077,9 +14973,9 @@ var PathScurryBase = class { process7(); return results; } - chdir(path5 = this.cwd) { + chdir(path6 = this.cwd) { const oldCwd = this.cwd; - this.cwd = typeof path5 === "string" ? this.cwd.resolve(path5) : path5; + this.cwd = typeof path6 === "string" ? this.cwd.resolve(path6) : path6; this.cwd[setAsCwd](oldCwd); } }; @@ -13435,8 +15331,8 @@ var MatchRecord = class { } // match, absolute, ifdir entries() { - return [...this.store.entries()].map(([path5, n]) => [ - path5, + return [...this.store.entries()].map(([path6, n]) => [ + path6, !!(n & 2), !!(n & 1) ]); @@ -13641,9 +15537,9 @@ var GlobUtil = class { signal; maxDepth; includeChildMatches; - constructor(patterns, path5, opts) { + constructor(patterns, path6, opts) { this.patterns = patterns; - this.path = path5; + this.path = path6; this.opts = opts; this.#sep = !opts.posix && opts.platform === "win32" ? "\\" : "/"; this.includeChildMatches = opts.includeChildMatches !== false; @@ -13662,11 +15558,11 @@ var GlobUtil = class { }); } } - #ignored(path5) { - return this.seen.has(path5) || !!this.#ignore?.ignored?.(path5); + #ignored(path6) { + return this.seen.has(path6) || !!this.#ignore?.ignored?.(path6); } - #childrenIgnored(path5) { - return !!this.#ignore?.childrenIgnored?.(path5); + #childrenIgnored(path6) { + return !!this.#ignore?.childrenIgnored?.(path6); } // backpressure mechanism pause() { @@ -13881,8 +15777,8 @@ var GlobUtil = class { }; var GlobWalker = class extends GlobUtil { matches = /* @__PURE__ */ new Set(); - constructor(patterns, path5, opts) { - super(patterns, path5, opts); + constructor(patterns, path6, opts) { + super(patterns, path6, opts); } matchEmit(e) { this.matches.add(e); @@ -13919,8 +15815,8 @@ var GlobWalker = class extends GlobUtil { }; var GlobStream = class extends GlobUtil { results; - constructor(patterns, path5, opts) { - super(patterns, path5, opts); + constructor(patterns, path6, opts) { + super(patterns, path6, opts); this.results = new Minipass({ signal: this.signal, objectMode: true @@ -14208,8 +16104,8 @@ var glob = Object.assign(glob_, { iterateSync, Glob, hasMagic, - escape, - unescape + escape: escape2, + unescape: unescape2 }); glob.glob = glob; @@ -14527,7 +16423,7 @@ async function loadSpec(filePath) { return import_yaml.default.parse(content); } async function saveSpec(spec, filePath) { - const dir = path4.dirname(filePath); + const dir = path5.dirname(filePath); await fs3.mkdir(dir, { recursive: true }); const isJson = filePath.endsWith(".json"); const content = isJson ? JSON.stringify(spec, null, 2) + "\n" : import_yaml.default.stringify(spec, { lineWidth: 0, aliasDuplicateObjects: false }); @@ -14603,7 +16499,7 @@ async function combineSpecs(files, outputPath, serverStrategy) { return; } let filesToCombine = files; - const tempDir = serverStrategy ? path4.join(path4.dirname(outputPath), ".temp-combine") : null; + const tempDir = serverStrategy ? path5.join(path5.dirname(outputPath), ".temp-combine") : null; try { if (serverStrategy && tempDir) { await fs3.mkdir(tempDir, { recursive: true }); @@ -14611,13 +16507,13 @@ async function combineSpecs(files, outputPath, serverStrategy) { for (let i = 0; i < files.length; i++) { const spec = await loadSpec(files[i]); const processed = processSpecForServers(spec, serverStrategy); - const tempFile = path4.join(tempDir, `temp-${i}.yaml`); + const tempFile = path5.join(tempDir, `temp-${i}.yaml`); await saveSpec(processed, tempFile); filesToCombine.push(tempFile); } } const jsonPath = outputPath.replace(/\.ya?ml$/, "") + ".json"; - const jsonDir = path4.dirname(jsonPath); + const jsonDir = path5.dirname(jsonPath); await fs3.mkdir(jsonDir, { recursive: true }); logger.debug(`Running: npx @redocly/cli join ... -o "${jsonPath}"`); const env = { ...process.env, NODE_ENV: "production" }; @@ -14674,7 +16570,7 @@ Make sure: const spec = await loadSpec(file); pathCountBefore += countPaths(spec); } - const outputDir = path4.dirname(outputPath); + const outputDir = path5.dirname(outputPath); await fs3.mkdir(outputDir, { recursive: true }); await combineSpecs(files, outputPath, serverStrategy); const combinedSpec = await loadSpec(outputPath); diff --git a/dist/prepareSwagger.js b/dist/prepareSwagger.js index 643f05e..8b0fe14 100644 --- a/dist/prepareSwagger.js +++ b/dist/prepareSwagger.js @@ -2640,7 +2640,7 @@ var require_libsodium_wrappers = __commonJS({ var r2, t = "uint8array", _ = a2.ready.then((function() { function t2() { if (0 !== r2._sodium_init()) throw new Error("libsodium was not correctly initialized."); - for (var a3 = ["crypto_aead_aegis128l_decrypt", "crypto_aead_aegis128l_decrypt_detached", "crypto_aead_aegis128l_encrypt", "crypto_aead_aegis128l_encrypt_detached", "crypto_aead_aegis128l_keygen", "crypto_aead_aegis256_decrypt", "crypto_aead_aegis256_decrypt_detached", "crypto_aead_aegis256_encrypt", "crypto_aead_aegis256_encrypt_detached", "crypto_aead_aegis256_keygen", "crypto_aead_chacha20poly1305_decrypt", "crypto_aead_chacha20poly1305_decrypt_detached", "crypto_aead_chacha20poly1305_encrypt", "crypto_aead_chacha20poly1305_encrypt_detached", "crypto_aead_chacha20poly1305_ietf_decrypt", "crypto_aead_chacha20poly1305_ietf_decrypt_detached", "crypto_aead_chacha20poly1305_ietf_encrypt", "crypto_aead_chacha20poly1305_ietf_encrypt_detached", "crypto_aead_chacha20poly1305_ietf_keygen", "crypto_aead_chacha20poly1305_keygen", "crypto_aead_xchacha20poly1305_ietf_decrypt", "crypto_aead_xchacha20poly1305_ietf_decrypt_detached", "crypto_aead_xchacha20poly1305_ietf_encrypt", "crypto_aead_xchacha20poly1305_ietf_encrypt_detached", "crypto_aead_xchacha20poly1305_ietf_keygen", "crypto_auth", "crypto_auth_hmacsha256", "crypto_auth_hmacsha256_final", "crypto_auth_hmacsha256_init", "crypto_auth_hmacsha256_keygen", "crypto_auth_hmacsha256_update", "crypto_auth_hmacsha256_verify", "crypto_auth_hmacsha512", "crypto_auth_hmacsha512256", "crypto_auth_hmacsha512256_final", "crypto_auth_hmacsha512256_init", "crypto_auth_hmacsha512256_keygen", "crypto_auth_hmacsha512256_update", "crypto_auth_hmacsha512256_verify", "crypto_auth_hmacsha512_final", "crypto_auth_hmacsha512_init", "crypto_auth_hmacsha512_keygen", "crypto_auth_hmacsha512_update", "crypto_auth_hmacsha512_verify", "crypto_auth_keygen", "crypto_auth_verify", "crypto_box_beforenm", "crypto_box_curve25519xchacha20poly1305_beforenm", "crypto_box_curve25519xchacha20poly1305_detached", "crypto_box_curve25519xchacha20poly1305_detached_afternm", "crypto_box_curve25519xchacha20poly1305_easy", "crypto_box_curve25519xchacha20poly1305_easy_afternm", "crypto_box_curve25519xchacha20poly1305_keypair", "crypto_box_curve25519xchacha20poly1305_open_detached", "crypto_box_curve25519xchacha20poly1305_open_detached_afternm", "crypto_box_curve25519xchacha20poly1305_open_easy", "crypto_box_curve25519xchacha20poly1305_open_easy_afternm", "crypto_box_curve25519xchacha20poly1305_seal", "crypto_box_curve25519xchacha20poly1305_seal_open", "crypto_box_curve25519xchacha20poly1305_seed_keypair", "crypto_box_detached", "crypto_box_easy", "crypto_box_easy_afternm", "crypto_box_keypair", "crypto_box_open_detached", "crypto_box_open_easy", "crypto_box_open_easy_afternm", "crypto_box_seal", "crypto_box_seal_open", "crypto_box_seed_keypair", "crypto_core_ed25519_add", "crypto_core_ed25519_from_hash", "crypto_core_ed25519_from_uniform", "crypto_core_ed25519_is_valid_point", "crypto_core_ed25519_random", "crypto_core_ed25519_scalar_add", "crypto_core_ed25519_scalar_complement", "crypto_core_ed25519_scalar_invert", "crypto_core_ed25519_scalar_mul", "crypto_core_ed25519_scalar_negate", "crypto_core_ed25519_scalar_random", "crypto_core_ed25519_scalar_reduce", "crypto_core_ed25519_scalar_sub", "crypto_core_ed25519_sub", "crypto_core_hchacha20", "crypto_core_hsalsa20", "crypto_core_ristretto255_add", "crypto_core_ristretto255_from_hash", "crypto_core_ristretto255_is_valid_point", "crypto_core_ristretto255_random", "crypto_core_ristretto255_scalar_add", "crypto_core_ristretto255_scalar_complement", "crypto_core_ristretto255_scalar_invert", "crypto_core_ristretto255_scalar_mul", "crypto_core_ristretto255_scalar_negate", "crypto_core_ristretto255_scalar_random", "crypto_core_ristretto255_scalar_reduce", "crypto_core_ristretto255_scalar_sub", "crypto_core_ristretto255_sub", "crypto_generichash", "crypto_generichash_blake2b_salt_personal", "crypto_generichash_final", "crypto_generichash_init", "crypto_generichash_keygen", "crypto_generichash_update", "crypto_hash", "crypto_hash_sha256", "crypto_hash_sha256_final", "crypto_hash_sha256_init", "crypto_hash_sha256_update", "crypto_hash_sha512", "crypto_hash_sha512_final", "crypto_hash_sha512_init", "crypto_hash_sha512_update", "crypto_kdf_derive_from_key", "crypto_kdf_keygen", "crypto_kx_client_session_keys", "crypto_kx_keypair", "crypto_kx_seed_keypair", "crypto_kx_server_session_keys", "crypto_onetimeauth", "crypto_onetimeauth_final", "crypto_onetimeauth_init", "crypto_onetimeauth_keygen", "crypto_onetimeauth_update", "crypto_onetimeauth_verify", "crypto_pwhash", "crypto_pwhash_scryptsalsa208sha256", "crypto_pwhash_scryptsalsa208sha256_ll", "crypto_pwhash_scryptsalsa208sha256_str", "crypto_pwhash_scryptsalsa208sha256_str_verify", "crypto_pwhash_str", "crypto_pwhash_str_needs_rehash", "crypto_pwhash_str_verify", "crypto_scalarmult", "crypto_scalarmult_base", "crypto_scalarmult_ed25519", "crypto_scalarmult_ed25519_base", "crypto_scalarmult_ed25519_base_noclamp", "crypto_scalarmult_ed25519_noclamp", "crypto_scalarmult_ristretto255", "crypto_scalarmult_ristretto255_base", "crypto_secretbox_detached", "crypto_secretbox_easy", "crypto_secretbox_keygen", "crypto_secretbox_open_detached", "crypto_secretbox_open_easy", "crypto_secretstream_xchacha20poly1305_init_pull", "crypto_secretstream_xchacha20poly1305_init_push", "crypto_secretstream_xchacha20poly1305_keygen", "crypto_secretstream_xchacha20poly1305_pull", "crypto_secretstream_xchacha20poly1305_push", "crypto_secretstream_xchacha20poly1305_rekey", "crypto_shorthash", "crypto_shorthash_keygen", "crypto_shorthash_siphashx24", "crypto_sign", "crypto_sign_detached", "crypto_sign_ed25519_pk_to_curve25519", "crypto_sign_ed25519_sk_to_curve25519", "crypto_sign_ed25519_sk_to_pk", "crypto_sign_ed25519_sk_to_seed", "crypto_sign_final_create", "crypto_sign_final_verify", "crypto_sign_init", "crypto_sign_keypair", "crypto_sign_open", "crypto_sign_seed_keypair", "crypto_sign_update", "crypto_sign_verify_detached", "crypto_stream_chacha20", "crypto_stream_chacha20_ietf_xor", "crypto_stream_chacha20_ietf_xor_ic", "crypto_stream_chacha20_keygen", "crypto_stream_chacha20_xor", "crypto_stream_chacha20_xor_ic", "crypto_stream_keygen", "crypto_stream_xchacha20_keygen", "crypto_stream_xchacha20_xor", "crypto_stream_xchacha20_xor_ic", "randombytes_buf", "randombytes_buf_deterministic", "randombytes_close", "randombytes_random", "randombytes_set_implementation", "randombytes_stir", "randombytes_uniform", "sodium_version_string"], t3 = [x, k, S, T, w, Y, B, A, M, I, K, N, L, O, U, C, P, R, X, G, D, F, V3, H, W, q, j, z, J, Q, Z, $, ee, ae, re, te, _e, ne, se, ce, he, oe, pe, ye, ie, le, ue, de, ve, ge, be, fe, me, Ee, xe, ke, Se, Te, we, Ye, Be, Ae, Me, Ie, Ke, Ne, Le, Oe, Ue, Ce, Pe, Re, Xe, Ge, De, Fe, Ve, He, We, qe, je, ze, Je, Qe, Ze, $e, ea, aa, ra, ta, _a, na, sa, ca, ha, oa, pa, ya, ia, la, ua, da, va, ga, ba, fa, ma, Ea, xa, ka, Sa, Ta, wa, Ya, Ba, Aa, Ma, Ia, Ka, Na, La, Oa, Ua, Ca, Pa, Ra, Xa, Ga, Da, Fa, Va, Ha, Wa, qa, ja, za, Ja, Qa, Za, $a, er, ar, rr, tr, _r, nr, sr, cr, hr, or, pr, yr, ir, lr, ur, dr, vr, gr, br, fr, mr, Er, xr, kr, Sr, Tr, wr, Yr, Br, Ar, Mr, Ir, Kr, Nr, Lr, Or, Ur, Cr, Pr, Rr, Xr, Gr, Dr, Fr, Vr, Hr, Wr, qr], _3 = 0; _3 < t3.length; _3++) "function" == typeof r2["_" + a3[_3]] && (e2[a3[_3]] = t3[_3]); + for (var a3 = ["crypto_aead_aegis128l_decrypt", "crypto_aead_aegis128l_decrypt_detached", "crypto_aead_aegis128l_encrypt", "crypto_aead_aegis128l_encrypt_detached", "crypto_aead_aegis128l_keygen", "crypto_aead_aegis256_decrypt", "crypto_aead_aegis256_decrypt_detached", "crypto_aead_aegis256_encrypt", "crypto_aead_aegis256_encrypt_detached", "crypto_aead_aegis256_keygen", "crypto_aead_chacha20poly1305_decrypt", "crypto_aead_chacha20poly1305_decrypt_detached", "crypto_aead_chacha20poly1305_encrypt", "crypto_aead_chacha20poly1305_encrypt_detached", "crypto_aead_chacha20poly1305_ietf_decrypt", "crypto_aead_chacha20poly1305_ietf_decrypt_detached", "crypto_aead_chacha20poly1305_ietf_encrypt", "crypto_aead_chacha20poly1305_ietf_encrypt_detached", "crypto_aead_chacha20poly1305_ietf_keygen", "crypto_aead_chacha20poly1305_keygen", "crypto_aead_xchacha20poly1305_ietf_decrypt", "crypto_aead_xchacha20poly1305_ietf_decrypt_detached", "crypto_aead_xchacha20poly1305_ietf_encrypt", "crypto_aead_xchacha20poly1305_ietf_encrypt_detached", "crypto_aead_xchacha20poly1305_ietf_keygen", "crypto_auth", "crypto_auth_hmacsha256", "crypto_auth_hmacsha256_final", "crypto_auth_hmacsha256_init", "crypto_auth_hmacsha256_keygen", "crypto_auth_hmacsha256_update", "crypto_auth_hmacsha256_verify", "crypto_auth_hmacsha512", "crypto_auth_hmacsha512256", "crypto_auth_hmacsha512256_final", "crypto_auth_hmacsha512256_init", "crypto_auth_hmacsha512256_keygen", "crypto_auth_hmacsha512256_update", "crypto_auth_hmacsha512256_verify", "crypto_auth_hmacsha512_final", "crypto_auth_hmacsha512_init", "crypto_auth_hmacsha512_keygen", "crypto_auth_hmacsha512_update", "crypto_auth_hmacsha512_verify", "crypto_auth_keygen", "crypto_auth_verify", "crypto_box_beforenm", "crypto_box_curve25519xchacha20poly1305_beforenm", "crypto_box_curve25519xchacha20poly1305_detached", "crypto_box_curve25519xchacha20poly1305_detached_afternm", "crypto_box_curve25519xchacha20poly1305_easy", "crypto_box_curve25519xchacha20poly1305_easy_afternm", "crypto_box_curve25519xchacha20poly1305_keypair", "crypto_box_curve25519xchacha20poly1305_open_detached", "crypto_box_curve25519xchacha20poly1305_open_detached_afternm", "crypto_box_curve25519xchacha20poly1305_open_easy", "crypto_box_curve25519xchacha20poly1305_open_easy_afternm", "crypto_box_curve25519xchacha20poly1305_seal", "crypto_box_curve25519xchacha20poly1305_seal_open", "crypto_box_curve25519xchacha20poly1305_seed_keypair", "crypto_box_detached", "crypto_box_easy", "crypto_box_easy_afternm", "crypto_box_keypair", "crypto_box_open_detached", "crypto_box_open_easy", "crypto_box_open_easy_afternm", "crypto_box_seal", "crypto_box_seal_open", "crypto_box_seed_keypair", "crypto_core_ed25519_add", "crypto_core_ed25519_from_hash", "crypto_core_ed25519_from_uniform", "crypto_core_ed25519_is_valid_point", "crypto_core_ed25519_random", "crypto_core_ed25519_scalar_add", "crypto_core_ed25519_scalar_complement", "crypto_core_ed25519_scalar_invert", "crypto_core_ed25519_scalar_mul", "crypto_core_ed25519_scalar_negate", "crypto_core_ed25519_scalar_random", "crypto_core_ed25519_scalar_reduce", "crypto_core_ed25519_scalar_sub", "crypto_core_ed25519_sub", "crypto_core_hchacha20", "crypto_core_hsalsa20", "crypto_core_ristretto255_add", "crypto_core_ristretto255_from_hash", "crypto_core_ristretto255_is_valid_point", "crypto_core_ristretto255_random", "crypto_core_ristretto255_scalar_add", "crypto_core_ristretto255_scalar_complement", "crypto_core_ristretto255_scalar_invert", "crypto_core_ristretto255_scalar_mul", "crypto_core_ristretto255_scalar_negate", "crypto_core_ristretto255_scalar_random", "crypto_core_ristretto255_scalar_reduce", "crypto_core_ristretto255_scalar_sub", "crypto_core_ristretto255_sub", "crypto_generichash", "crypto_generichash_blake2b_salt_personal", "crypto_generichash_final", "crypto_generichash_init", "crypto_generichash_keygen", "crypto_generichash_update", "crypto_hash", "crypto_hash_sha256", "crypto_hash_sha256_final", "crypto_hash_sha256_init", "crypto_hash_sha256_update", "crypto_hash_sha512", "crypto_hash_sha512_final", "crypto_hash_sha512_init", "crypto_hash_sha512_update", "crypto_kdf_derive_from_key", "crypto_kdf_keygen", "crypto_kx_client_session_keys", "crypto_kx_keypair", "crypto_kx_seed_keypair", "crypto_kx_server_session_keys", "crypto_onetimeauth", "crypto_onetimeauth_final", "crypto_onetimeauth_init", "crypto_onetimeauth_keygen", "crypto_onetimeauth_update", "crypto_onetimeauth_verify", "crypto_pwhash", "crypto_pwhash_scryptsalsa208sha256", "crypto_pwhash_scryptsalsa208sha256_ll", "crypto_pwhash_scryptsalsa208sha256_str", "crypto_pwhash_scryptsalsa208sha256_str_verify", "crypto_pwhash_str", "crypto_pwhash_str_needs_rehash", "crypto_pwhash_str_verify", "crypto_scalarmult", "crypto_scalarmult_base", "crypto_scalarmult_ed25519", "crypto_scalarmult_ed25519_base", "crypto_scalarmult_ed25519_base_noclamp", "crypto_scalarmult_ed25519_noclamp", "crypto_scalarmult_ristretto255", "crypto_scalarmult_ristretto255_base", "crypto_secretbox_detached", "crypto_secretbox_easy", "crypto_secretbox_keygen", "crypto_secretbox_open_detached", "crypto_secretbox_open_easy", "crypto_secretstream_xchacha20poly1305_init_pull", "crypto_secretstream_xchacha20poly1305_init_push", "crypto_secretstream_xchacha20poly1305_keygen", "crypto_secretstream_xchacha20poly1305_pull", "crypto_secretstream_xchacha20poly1305_push", "crypto_secretstream_xchacha20poly1305_rekey", "crypto_shorthash", "crypto_shorthash_keygen", "crypto_shorthash_siphashx24", "crypto_sign", "crypto_sign_detached", "crypto_sign_ed25519_pk_to_curve25519", "crypto_sign_ed25519_sk_to_curve25519", "crypto_sign_ed25519_sk_to_pk", "crypto_sign_ed25519_sk_to_seed", "crypto_sign_final_create", "crypto_sign_final_verify", "crypto_sign_init", "crypto_sign_keypair", "crypto_sign_open", "crypto_sign_seed_keypair", "crypto_sign_update", "crypto_sign_verify_detached", "crypto_stream_chacha20", "crypto_stream_chacha20_ietf_xor", "crypto_stream_chacha20_ietf_xor_ic", "crypto_stream_chacha20_keygen", "crypto_stream_chacha20_xor", "crypto_stream_chacha20_xor_ic", "crypto_stream_keygen", "crypto_stream_xchacha20_keygen", "crypto_stream_xchacha20_xor", "crypto_stream_xchacha20_xor_ic", "randombytes_buf", "randombytes_buf_deterministic", "randombytes_close", "randombytes_random", "randombytes_set_implementation", "randombytes_stir", "randombytes_uniform", "sodium_version_string"], t3 = [x, k, S, T, w, Y, B, A, M, I, K, N, L, O, U, C, P, R, X, G, D, F, V3, H, W, q, j, z, J, Q, Z, $, ee, ae, re, te, _e, ne, se, ce, he, oe, pe, ye, ie, le, ue, de, ve, ge, be, fe, me, Ee, xe, ke, Se, Te, we, Ye, Be, Ae, Me, Ie, Ke, Ne, Le, Oe, Ue, Ce, Pe, Re, Xe, Ge, De, Fe, Ve, He, We, qe, je, ze, Je, Qe, Ze, $e, ea, aa, ra, ta, _a2, na, sa, ca, ha, oa, pa, ya, ia, la, ua, da, va, ga, ba, fa, ma, Ea, xa, ka, Sa, Ta, wa, Ya, Ba, Aa, Ma, Ia, Ka, Na, La, Oa, Ua, Ca, Pa, Ra, Xa, Ga, Da, Fa, Va, Ha, Wa, qa, ja, za, Ja, Qa, Za, $a, er, ar, rr, tr, _r, nr, sr, cr, hr, or, pr, yr, ir, lr, ur, dr, vr, gr, br, fr, mr, Er, xr, kr, Sr, Tr, wr, Yr, Br, Ar, Mr, Ir, Kr, Nr, Lr, Or, Ur, Cr, Pr, Rr, Xr, Gr, Dr, Fr, Vr, Hr, Wr, qr], _3 = 0; _3 < t3.length; _3++) "function" == typeof r2["_" + a3[_3]] && (e2[a3[_3]] = t3[_3]); var n3 = ["SODIUM_LIBRARY_VERSION_MAJOR", "SODIUM_LIBRARY_VERSION_MINOR", "crypto_aead_aegis128l_ABYTES", "crypto_aead_aegis128l_KEYBYTES", "crypto_aead_aegis128l_MESSAGEBYTES_MAX", "crypto_aead_aegis128l_NPUBBYTES", "crypto_aead_aegis128l_NSECBYTES", "crypto_aead_aegis256_ABYTES", "crypto_aead_aegis256_KEYBYTES", "crypto_aead_aegis256_MESSAGEBYTES_MAX", "crypto_aead_aegis256_NPUBBYTES", "crypto_aead_aegis256_NSECBYTES", "crypto_aead_aes256gcm_ABYTES", "crypto_aead_aes256gcm_KEYBYTES", "crypto_aead_aes256gcm_MESSAGEBYTES_MAX", "crypto_aead_aes256gcm_NPUBBYTES", "crypto_aead_aes256gcm_NSECBYTES", "crypto_aead_chacha20poly1305_ABYTES", "crypto_aead_chacha20poly1305_IETF_ABYTES", "crypto_aead_chacha20poly1305_IETF_KEYBYTES", "crypto_aead_chacha20poly1305_IETF_MESSAGEBYTES_MAX", "crypto_aead_chacha20poly1305_IETF_NPUBBYTES", "crypto_aead_chacha20poly1305_IETF_NSECBYTES", "crypto_aead_chacha20poly1305_KEYBYTES", "crypto_aead_chacha20poly1305_MESSAGEBYTES_MAX", "crypto_aead_chacha20poly1305_NPUBBYTES", "crypto_aead_chacha20poly1305_NSECBYTES", "crypto_aead_chacha20poly1305_ietf_ABYTES", "crypto_aead_chacha20poly1305_ietf_KEYBYTES", "crypto_aead_chacha20poly1305_ietf_MESSAGEBYTES_MAX", "crypto_aead_chacha20poly1305_ietf_NPUBBYTES", "crypto_aead_chacha20poly1305_ietf_NSECBYTES", "crypto_aead_xchacha20poly1305_IETF_ABYTES", "crypto_aead_xchacha20poly1305_IETF_KEYBYTES", "crypto_aead_xchacha20poly1305_IETF_MESSAGEBYTES_MAX", "crypto_aead_xchacha20poly1305_IETF_NPUBBYTES", "crypto_aead_xchacha20poly1305_IETF_NSECBYTES", "crypto_aead_xchacha20poly1305_ietf_ABYTES", "crypto_aead_xchacha20poly1305_ietf_KEYBYTES", "crypto_aead_xchacha20poly1305_ietf_MESSAGEBYTES_MAX", "crypto_aead_xchacha20poly1305_ietf_NPUBBYTES", "crypto_aead_xchacha20poly1305_ietf_NSECBYTES", "crypto_auth_BYTES", "crypto_auth_KEYBYTES", "crypto_auth_hmacsha256_BYTES", "crypto_auth_hmacsha256_KEYBYTES", "crypto_auth_hmacsha512256_BYTES", "crypto_auth_hmacsha512256_KEYBYTES", "crypto_auth_hmacsha512_BYTES", "crypto_auth_hmacsha512_KEYBYTES", "crypto_box_BEFORENMBYTES", "crypto_box_MACBYTES", "crypto_box_MESSAGEBYTES_MAX", "crypto_box_NONCEBYTES", "crypto_box_PUBLICKEYBYTES", "crypto_box_SEALBYTES", "crypto_box_SECRETKEYBYTES", "crypto_box_SEEDBYTES", "crypto_box_curve25519xchacha20poly1305_BEFORENMBYTES", "crypto_box_curve25519xchacha20poly1305_MACBYTES", "crypto_box_curve25519xchacha20poly1305_MESSAGEBYTES_MAX", "crypto_box_curve25519xchacha20poly1305_NONCEBYTES", "crypto_box_curve25519xchacha20poly1305_PUBLICKEYBYTES", "crypto_box_curve25519xchacha20poly1305_SEALBYTES", "crypto_box_curve25519xchacha20poly1305_SECRETKEYBYTES", "crypto_box_curve25519xchacha20poly1305_SEEDBYTES", "crypto_box_curve25519xsalsa20poly1305_BEFORENMBYTES", "crypto_box_curve25519xsalsa20poly1305_MACBYTES", "crypto_box_curve25519xsalsa20poly1305_MESSAGEBYTES_MAX", "crypto_box_curve25519xsalsa20poly1305_NONCEBYTES", "crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES", "crypto_box_curve25519xsalsa20poly1305_SECRETKEYBYTES", "crypto_box_curve25519xsalsa20poly1305_SEEDBYTES", "crypto_core_ed25519_BYTES", "crypto_core_ed25519_HASHBYTES", "crypto_core_ed25519_NONREDUCEDSCALARBYTES", "crypto_core_ed25519_SCALARBYTES", "crypto_core_ed25519_UNIFORMBYTES", "crypto_core_hchacha20_CONSTBYTES", "crypto_core_hchacha20_INPUTBYTES", "crypto_core_hchacha20_KEYBYTES", "crypto_core_hchacha20_OUTPUTBYTES", "crypto_core_hsalsa20_CONSTBYTES", "crypto_core_hsalsa20_INPUTBYTES", "crypto_core_hsalsa20_KEYBYTES", "crypto_core_hsalsa20_OUTPUTBYTES", "crypto_core_ristretto255_BYTES", "crypto_core_ristretto255_HASHBYTES", "crypto_core_ristretto255_NONREDUCEDSCALARBYTES", "crypto_core_ristretto255_SCALARBYTES", "crypto_core_salsa2012_CONSTBYTES", "crypto_core_salsa2012_INPUTBYTES", "crypto_core_salsa2012_KEYBYTES", "crypto_core_salsa2012_OUTPUTBYTES", "crypto_core_salsa208_CONSTBYTES", "crypto_core_salsa208_INPUTBYTES", "crypto_core_salsa208_KEYBYTES", "crypto_core_salsa208_OUTPUTBYTES", "crypto_core_salsa20_CONSTBYTES", "crypto_core_salsa20_INPUTBYTES", "crypto_core_salsa20_KEYBYTES", "crypto_core_salsa20_OUTPUTBYTES", "crypto_generichash_BYTES", "crypto_generichash_BYTES_MAX", "crypto_generichash_BYTES_MIN", "crypto_generichash_KEYBYTES", "crypto_generichash_KEYBYTES_MAX", "crypto_generichash_KEYBYTES_MIN", "crypto_generichash_blake2b_BYTES", "crypto_generichash_blake2b_BYTES_MAX", "crypto_generichash_blake2b_BYTES_MIN", "crypto_generichash_blake2b_KEYBYTES", "crypto_generichash_blake2b_KEYBYTES_MAX", "crypto_generichash_blake2b_KEYBYTES_MIN", "crypto_generichash_blake2b_PERSONALBYTES", "crypto_generichash_blake2b_SALTBYTES", "crypto_hash_BYTES", "crypto_hash_sha256_BYTES", "crypto_hash_sha512_BYTES", "crypto_kdf_BYTES_MAX", "crypto_kdf_BYTES_MIN", "crypto_kdf_CONTEXTBYTES", "crypto_kdf_KEYBYTES", "crypto_kdf_blake2b_BYTES_MAX", "crypto_kdf_blake2b_BYTES_MIN", "crypto_kdf_blake2b_CONTEXTBYTES", "crypto_kdf_blake2b_KEYBYTES", "crypto_kdf_hkdf_sha256_BYTES_MAX", "crypto_kdf_hkdf_sha256_BYTES_MIN", "crypto_kdf_hkdf_sha256_KEYBYTES", "crypto_kdf_hkdf_sha512_BYTES_MAX", "crypto_kdf_hkdf_sha512_BYTES_MIN", "crypto_kdf_hkdf_sha512_KEYBYTES", "crypto_kx_PUBLICKEYBYTES", "crypto_kx_SECRETKEYBYTES", "crypto_kx_SEEDBYTES", "crypto_kx_SESSIONKEYBYTES", "crypto_onetimeauth_BYTES", "crypto_onetimeauth_KEYBYTES", "crypto_onetimeauth_poly1305_BYTES", "crypto_onetimeauth_poly1305_KEYBYTES", "crypto_pwhash_ALG_ARGON2I13", "crypto_pwhash_ALG_ARGON2ID13", "crypto_pwhash_ALG_DEFAULT", "crypto_pwhash_BYTES_MAX", "crypto_pwhash_BYTES_MIN", "crypto_pwhash_MEMLIMIT_INTERACTIVE", "crypto_pwhash_MEMLIMIT_MAX", "crypto_pwhash_MEMLIMIT_MIN", "crypto_pwhash_MEMLIMIT_MODERATE", "crypto_pwhash_MEMLIMIT_SENSITIVE", "crypto_pwhash_OPSLIMIT_INTERACTIVE", "crypto_pwhash_OPSLIMIT_MAX", "crypto_pwhash_OPSLIMIT_MIN", "crypto_pwhash_OPSLIMIT_MODERATE", "crypto_pwhash_OPSLIMIT_SENSITIVE", "crypto_pwhash_PASSWD_MAX", "crypto_pwhash_PASSWD_MIN", "crypto_pwhash_SALTBYTES", "crypto_pwhash_STRBYTES", "crypto_pwhash_argon2i_BYTES_MAX", "crypto_pwhash_argon2i_BYTES_MIN", "crypto_pwhash_argon2i_MEMLIMIT_INTERACTIVE", "crypto_pwhash_argon2i_MEMLIMIT_MAX", "crypto_pwhash_argon2i_MEMLIMIT_MIN", "crypto_pwhash_argon2i_MEMLIMIT_MODERATE", "crypto_pwhash_argon2i_MEMLIMIT_SENSITIVE", "crypto_pwhash_argon2i_OPSLIMIT_INTERACTIVE", "crypto_pwhash_argon2i_OPSLIMIT_MAX", "crypto_pwhash_argon2i_OPSLIMIT_MIN", "crypto_pwhash_argon2i_OPSLIMIT_MODERATE", "crypto_pwhash_argon2i_OPSLIMIT_SENSITIVE", "crypto_pwhash_argon2i_PASSWD_MAX", "crypto_pwhash_argon2i_PASSWD_MIN", "crypto_pwhash_argon2i_SALTBYTES", "crypto_pwhash_argon2i_STRBYTES", "crypto_pwhash_argon2id_BYTES_MAX", "crypto_pwhash_argon2id_BYTES_MIN", "crypto_pwhash_argon2id_MEMLIMIT_INTERACTIVE", "crypto_pwhash_argon2id_MEMLIMIT_MAX", "crypto_pwhash_argon2id_MEMLIMIT_MIN", "crypto_pwhash_argon2id_MEMLIMIT_MODERATE", "crypto_pwhash_argon2id_MEMLIMIT_SENSITIVE", "crypto_pwhash_argon2id_OPSLIMIT_INTERACTIVE", "crypto_pwhash_argon2id_OPSLIMIT_MAX", "crypto_pwhash_argon2id_OPSLIMIT_MIN", "crypto_pwhash_argon2id_OPSLIMIT_MODERATE", "crypto_pwhash_argon2id_OPSLIMIT_SENSITIVE", "crypto_pwhash_argon2id_PASSWD_MAX", "crypto_pwhash_argon2id_PASSWD_MIN", "crypto_pwhash_argon2id_SALTBYTES", "crypto_pwhash_argon2id_STRBYTES", "crypto_pwhash_scryptsalsa208sha256_BYTES_MAX", "crypto_pwhash_scryptsalsa208sha256_BYTES_MIN", "crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_INTERACTIVE", "crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX", "crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN", "crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_SENSITIVE", "crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_INTERACTIVE", "crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX", "crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN", "crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_SENSITIVE", "crypto_pwhash_scryptsalsa208sha256_PASSWD_MAX", "crypto_pwhash_scryptsalsa208sha256_PASSWD_MIN", "crypto_pwhash_scryptsalsa208sha256_SALTBYTES", "crypto_pwhash_scryptsalsa208sha256_STRBYTES", "crypto_scalarmult_BYTES", "crypto_scalarmult_SCALARBYTES", "crypto_scalarmult_curve25519_BYTES", "crypto_scalarmult_curve25519_SCALARBYTES", "crypto_scalarmult_ed25519_BYTES", "crypto_scalarmult_ed25519_SCALARBYTES", "crypto_scalarmult_ristretto255_BYTES", "crypto_scalarmult_ristretto255_SCALARBYTES", "crypto_secretbox_KEYBYTES", "crypto_secretbox_MACBYTES", "crypto_secretbox_MESSAGEBYTES_MAX", "crypto_secretbox_NONCEBYTES", "crypto_secretbox_xchacha20poly1305_KEYBYTES", "crypto_secretbox_xchacha20poly1305_MACBYTES", "crypto_secretbox_xchacha20poly1305_MESSAGEBYTES_MAX", "crypto_secretbox_xchacha20poly1305_NONCEBYTES", "crypto_secretbox_xsalsa20poly1305_KEYBYTES", "crypto_secretbox_xsalsa20poly1305_MACBYTES", "crypto_secretbox_xsalsa20poly1305_MESSAGEBYTES_MAX", "crypto_secretbox_xsalsa20poly1305_NONCEBYTES", "crypto_secretstream_xchacha20poly1305_ABYTES", "crypto_secretstream_xchacha20poly1305_HEADERBYTES", "crypto_secretstream_xchacha20poly1305_KEYBYTES", "crypto_secretstream_xchacha20poly1305_MESSAGEBYTES_MAX", "crypto_secretstream_xchacha20poly1305_TAG_FINAL", "crypto_secretstream_xchacha20poly1305_TAG_MESSAGE", "crypto_secretstream_xchacha20poly1305_TAG_PUSH", "crypto_secretstream_xchacha20poly1305_TAG_REKEY", "crypto_shorthash_BYTES", "crypto_shorthash_KEYBYTES", "crypto_shorthash_siphash24_BYTES", "crypto_shorthash_siphash24_KEYBYTES", "crypto_shorthash_siphashx24_BYTES", "crypto_shorthash_siphashx24_KEYBYTES", "crypto_sign_BYTES", "crypto_sign_MESSAGEBYTES_MAX", "crypto_sign_PUBLICKEYBYTES", "crypto_sign_SECRETKEYBYTES", "crypto_sign_SEEDBYTES", "crypto_sign_ed25519_BYTES", "crypto_sign_ed25519_MESSAGEBYTES_MAX", "crypto_sign_ed25519_PUBLICKEYBYTES", "crypto_sign_ed25519_SECRETKEYBYTES", "crypto_sign_ed25519_SEEDBYTES", "crypto_stream_KEYBYTES", "crypto_stream_MESSAGEBYTES_MAX", "crypto_stream_NONCEBYTES", "crypto_stream_chacha20_IETF_KEYBYTES", "crypto_stream_chacha20_IETF_MESSAGEBYTES_MAX", "crypto_stream_chacha20_IETF_NONCEBYTES", "crypto_stream_chacha20_KEYBYTES", "crypto_stream_chacha20_MESSAGEBYTES_MAX", "crypto_stream_chacha20_NONCEBYTES", "crypto_stream_chacha20_ietf_KEYBYTES", "crypto_stream_chacha20_ietf_MESSAGEBYTES_MAX", "crypto_stream_chacha20_ietf_NONCEBYTES", "crypto_stream_salsa2012_KEYBYTES", "crypto_stream_salsa2012_MESSAGEBYTES_MAX", "crypto_stream_salsa2012_NONCEBYTES", "crypto_stream_salsa208_KEYBYTES", "crypto_stream_salsa208_MESSAGEBYTES_MAX", "crypto_stream_salsa208_NONCEBYTES", "crypto_stream_salsa20_KEYBYTES", "crypto_stream_salsa20_MESSAGEBYTES_MAX", "crypto_stream_salsa20_NONCEBYTES", "crypto_stream_xchacha20_KEYBYTES", "crypto_stream_xchacha20_MESSAGEBYTES_MAX", "crypto_stream_xchacha20_NONCEBYTES", "crypto_stream_xsalsa20_KEYBYTES", "crypto_stream_xsalsa20_MESSAGEBYTES_MAX", "crypto_stream_xsalsa20_NONCEBYTES", "crypto_verify_16_BYTES", "crypto_verify_32_BYTES", "crypto_verify_64_BYTES"]; for (_3 = 0; _3 < n3.length; _3++) "function" == typeof (c3 = r2["_" + n3[_3].toLowerCase()]) && (e2[n3[_3]] = c3()); var s3 = ["SODIUM_VERSION_STRING", "crypto_pwhash_STRPREFIX", "crypto_pwhash_argon2i_STRPREFIX", "crypto_pwhash_argon2id_STRPREFIX", "crypto_pwhash_scryptsalsa208sha256_STRPREFIX"]; @@ -4052,7 +4052,7 @@ var require_libsodium_wrappers = __commonJS({ var n2 = y(t2, e3); return g(a3), n2; } - function _a(e3, a3, t2) { + function _a2(e3, a3, t2) { var _2 = []; l(t2), e3 = E(_2, e3, "x"); var n2, s2 = 0 | r2._crypto_core_ristretto255_scalarbytes(); @@ -8511,7 +8511,7 @@ var require_lodash = __commonJS({ var nativeKeys = overArg(Object.keys, Object); var nativeMax = Math.max; function arrayLikeKeys(value, inherited) { - var result = isArray3(value) || isArguments(value) ? baseTimes(value.length, String) : []; + var result = isArray4(value) || isArguments(value) ? baseTimes(value.length, String) : []; var length = result.length, skipIndexes = !!length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && (key == "length" || isIndex(key, length)))) { @@ -8552,7 +8552,7 @@ var require_lodash = __commonJS({ function isArguments(value) { return isArrayLikeObject(value) && hasOwnProperty.call(value, "callee") && (!propertyIsEnumerable.call(value, "callee") || objectToString.call(value) == argsTag); } - var isArray3 = Array.isArray; + var isArray4 = Array.isArray; function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } @@ -8574,7 +8574,7 @@ var require_lodash = __commonJS({ return !!value && typeof value == "object"; } function isString(value) { - return typeof value == "string" || !isArray3(value) && isObjectLike(value) && objectToString.call(value) == stringTag; + return typeof value == "string" || !isArray4(value) && isObjectLike(value) && objectToString.call(value) == stringTag; } function isSymbol(value) { return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag; @@ -8768,12 +8768,12 @@ var require_lodash6 = __commonJS({ var stringTag = "[object String]"; var objectProto = Object.prototype; var objectToString = objectProto.toString; - var isArray3 = Array.isArray; + var isArray4 = Array.isArray; function isObjectLike(value) { return !!value && typeof value == "object"; } function isString(value) { - return typeof value == "string" || !isArray3(value) && isObjectLike(value) && objectToString.call(value) == stringTag; + return typeof value == "string" || !isArray4(value) && isObjectLike(value) && objectToString.call(value) == stringTag; } module2.exports = isString; } @@ -9101,7 +9101,7 @@ var require_jsonwebtoken = __commonJS({ // src/prepareSwagger.ts var fs3 = __toESM(require("node:fs")); -var path5 = __toESM(require("node:path")); +var path6 = __toESM(require("node:path")); // node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/context.js var import_node_process = __toESM(require("node:process"), 1); @@ -9476,6 +9476,1899 @@ function logging() { return cachedLogging; } +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/tslib.mjs +function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") + throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; +} +function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/uuid.mjs +var uuid4 = function() { + const { crypto: crypto2 } = globalThis; + if (crypto2?.randomUUID) { + uuid4 = crypto2.randomUUID.bind(crypto2); + return crypto2.randomUUID(); + } + const u8 = new Uint8Array(1); + const randomByte = crypto2 ? () => crypto2.getRandomValues(u8)[0] : () => Math.random() * 255 & 255; + return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16)); +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/errors.mjs +function isAbortError(err) { + return typeof err === "object" && err !== null && // Spec-compliant fetch implementations + ("name" in err && err.name === "AbortError" || // Expo fetch + "message" in err && String(err.message).includes("FetchRequestCanceledException")); +} +var castToError = (err) => { + if (err instanceof Error) + return err; + if (typeof err === "object" && err !== null) { + try { + if (Object.prototype.toString.call(err) === "[object Error]") { + const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); + if (err.stack) + error.stack = err.stack; + if (err.cause && !error.cause) + error.cause = err.cause; + if (err.name) + error.name = err.name; + return error; + } + } catch { + } + try { + return new Error(JSON.stringify(err)); + } catch { + } + } + return new Error(err); +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/core/error.mjs +var StainlessError = class extends Error { +}; +var APIError = class _APIError extends StainlessError { + constructor(status, error, message, headers) { + super(`${_APIError.makeMessage(status, error, message)}`); + this.status = status; + this.headers = headers; + this.error = error; + } + static makeMessage(status, error, message) { + const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message; + if (status && msg) { + return `${status} ${msg}`; + } + if (status) { + return `${status} status code (no body)`; + } + if (msg) { + return msg; + } + return "(no status code or body)"; + } + static generate(status, errorResponse, message, headers) { + if (!status || !headers) { + return new APIConnectionError({ message, cause: castToError(errorResponse) }); + } + const error = errorResponse; + if (status === 400) { + return new BadRequestError(status, error, message, headers); + } + if (status === 401) { + return new AuthenticationError(status, error, message, headers); + } + if (status === 403) { + return new PermissionDeniedError(status, error, message, headers); + } + if (status === 404) { + return new NotFoundError(status, error, message, headers); + } + if (status === 409) { + return new ConflictError(status, error, message, headers); + } + if (status === 422) { + return new UnprocessableEntityError(status, error, message, headers); + } + if (status === 429) { + return new RateLimitError(status, error, message, headers); + } + if (status >= 500) { + return new InternalServerError(status, error, message, headers); + } + return new _APIError(status, error, message, headers); + } +}; +var APIUserAbortError = class extends APIError { + constructor({ message } = {}) { + super(void 0, void 0, message || "Request was aborted.", void 0); + } +}; +var APIConnectionError = class extends APIError { + constructor({ message, cause }) { + super(void 0, void 0, message || "Connection error.", void 0); + if (cause) + this.cause = cause; + } +}; +var APIConnectionTimeoutError = class extends APIConnectionError { + constructor({ message } = {}) { + super({ message: message ?? "Request timed out." }); + } +}; +var BadRequestError = class extends APIError { +}; +var AuthenticationError = class extends APIError { +}; +var PermissionDeniedError = class extends APIError { +}; +var NotFoundError = class extends APIError { +}; +var ConflictError = class extends APIError { +}; +var UnprocessableEntityError = class extends APIError { +}; +var RateLimitError = class extends APIError { +}; +var InternalServerError = class extends APIError { +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/values.mjs +var startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; +var isAbsoluteURL = (url) => { + return startsWithSchemeRegexp.test(url); +}; +var isArray = (val) => (isArray = Array.isArray, isArray(val)); +var isReadonlyArray = isArray; +function maybeObj(x) { + if (typeof x !== "object") { + return {}; + } + return x ?? {}; +} +function isEmptyObj(obj) { + if (!obj) + return true; + for (const _k in obj) + return false; + return true; +} +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +var validatePositiveInteger = (name, n) => { + if (typeof n !== "number" || !Number.isInteger(n)) { + throw new StainlessError(`${name} must be an integer`); + } + if (n < 0) { + throw new StainlessError(`${name} must be a positive integer`); + } + return n; +}; +var safeJSON = (text) => { + try { + return JSON.parse(text); + } catch (err) { + return void 0; + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/sleep.mjs +var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/version.mjs +var VERSION = "0.5.0"; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/detect-platform.mjs +function getDetectedPlatform() { + if (typeof Deno !== "undefined" && Deno.build != null) { + return "deno"; + } + if (typeof EdgeRuntime !== "undefined") { + return "edge"; + } + if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") { + return "node"; + } + return "unknown"; +} +var getPlatformProperties = () => { + const detectedPlatform = getDetectedPlatform(); + if (detectedPlatform === "deno") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": normalizePlatform(Deno.build.os), + "X-Stainless-Arch": normalizeArch(Deno.build.arch), + "X-Stainless-Runtime": "deno", + "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown" + }; + } + if (typeof EdgeRuntime !== "undefined") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": `other:${EdgeRuntime}`, + "X-Stainless-Runtime": "edge", + "X-Stainless-Runtime-Version": globalThis.process.version + }; + } + if (detectedPlatform === "node") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": normalizePlatform(globalThis.process.platform ?? "unknown"), + "X-Stainless-Arch": normalizeArch(globalThis.process.arch ?? "unknown"), + "X-Stainless-Runtime": "node", + "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown" + }; + } + const browserInfo = getBrowserInfo(); + if (browserInfo) { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": "unknown", + "X-Stainless-Runtime": `browser:${browserInfo.browser}`, + "X-Stainless-Runtime-Version": browserInfo.version + }; + } + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": "unknown", + "X-Stainless-Runtime": "unknown", + "X-Stainless-Runtime-Version": "unknown" + }; +}; +function getBrowserInfo() { + if (typeof navigator === "undefined" || !navigator) { + return null; + } + const browserPatterns = [ + { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ } + ]; + for (const { key, pattern } of browserPatterns) { + const match = pattern.exec(navigator.userAgent); + if (match) { + const major = match[1] || 0; + const minor = match[2] || 0; + const patch = match[3] || 0; + return { browser: key, version: `${major}.${minor}.${patch}` }; + } + } + return null; +} +var normalizeArch = (arch) => { + if (arch === "x32") + return "x32"; + if (arch === "x86_64" || arch === "x64") + return "x64"; + if (arch === "arm") + return "arm"; + if (arch === "aarch64" || arch === "arm64") + return "arm64"; + if (arch) + return `other:${arch}`; + return "unknown"; +}; +var normalizePlatform = (platform) => { + platform = platform.toLowerCase(); + if (platform.includes("ios")) + return "iOS"; + if (platform === "android") + return "Android"; + if (platform === "darwin") + return "MacOS"; + if (platform === "win32") + return "Windows"; + if (platform === "freebsd") + return "FreeBSD"; + if (platform === "openbsd") + return "OpenBSD"; + if (platform === "linux") + return "Linux"; + if (platform) + return `Other:${platform}`; + return "Unknown"; +}; +var _platformHeaders; +var getPlatformHeaders = () => { + return _platformHeaders ?? (_platformHeaders = getPlatformProperties()); +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/shims.mjs +function getDefaultFetch() { + if (typeof fetch !== "undefined") { + return fetch; + } + throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Stainless({ fetch })` or polyfill the global, `globalThis.fetch = fetch`"); +} +function makeReadableStream(...args) { + const ReadableStream = globalThis.ReadableStream; + if (typeof ReadableStream === "undefined") { + throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`"); + } + return new ReadableStream(...args); +} +function ReadableStreamFrom(iterable) { + let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); + return makeReadableStream({ + start() { + }, + async pull(controller) { + const { done, value } = await iter.next(); + if (done) { + controller.close(); + } else { + controller.enqueue(value); + } + }, + async cancel() { + await iter.return?.(); + } + }); +} +async function CancelReadableStream(stream) { + if (stream === null || typeof stream !== "object") + return; + if (stream[Symbol.asyncIterator]) { + await stream[Symbol.asyncIterator]().return?.(); + return; + } + const reader = stream.getReader(); + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/request-options.mjs +var FallbackEncoder = ({ headers, body }) => { + return { + bodyHeaders: { + "content-type": "application/json" + }, + body: JSON.stringify(body) + }; +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/qs/formats.mjs +var default_format = "RFC3986"; +var default_formatter = (v) => String(v); +var formatters = { + RFC1738: (v) => String(v).replace(/%20/g, "+"), + RFC3986: default_formatter +}; +var RFC1738 = "RFC1738"; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/qs/utils.mjs +var has = (obj, key) => (has = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has(obj, key)); +var hex_table = /* @__PURE__ */ (() => { + const array = []; + for (let i = 0; i < 256; ++i) { + array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase()); + } + return array; +})(); +var limit = 1024; +var encode = (str, _defaultEncoder, charset, _kind, format) => { + if (str.length === 0) { + return str; + } + let string = str; + if (typeof str === "symbol") { + string = Symbol.prototype.toString.call(str); + } else if (typeof str !== "string") { + string = String(str); + } + if (charset === "iso-8859-1") { + return escape(string).replace(/%u[0-9a-f]{4}/gi, function($0) { + return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; + }); + } + let out = ""; + for (let j = 0; j < string.length; j += limit) { + const segment = string.length >= limit ? string.slice(j, j + limit) : string; + const arr = []; + for (let i = 0; i < segment.length; ++i) { + let c = segment.charCodeAt(i); + if (c === 45 || // - + c === 46 || // . + c === 95 || // _ + c === 126 || // ~ + c >= 48 && c <= 57 || // 0-9 + c >= 65 && c <= 90 || // a-z + c >= 97 && c <= 122 || // A-Z + format === RFC1738 && (c === 40 || c === 41)) { + arr[arr.length] = segment.charAt(i); + continue; + } + if (c < 128) { + arr[arr.length] = hex_table[c]; + continue; + } + if (c < 2048) { + arr[arr.length] = hex_table[192 | c >> 6] + hex_table[128 | c & 63]; + continue; + } + if (c < 55296 || c >= 57344) { + arr[arr.length] = hex_table[224 | c >> 12] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63]; + continue; + } + i += 1; + c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023); + arr[arr.length] = hex_table[240 | c >> 18] + hex_table[128 | c >> 12 & 63] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63]; + } + out += arr.join(""); + } + return out; +}; +function is_buffer(obj) { + if (!obj || typeof obj !== "object") { + return false; + } + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +} +function maybe_map(val, fn) { + if (isArray(val)) { + const mapped = []; + for (let i = 0; i < val.length; i += 1) { + mapped.push(fn(val[i])); + } + return mapped; + } + return fn(val); +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/qs/stringify.mjs +var array_prefix_generators = { + brackets(prefix) { + return String(prefix) + "[]"; + }, + comma: "comma", + indices(prefix, key) { + return String(prefix) + "[" + key + "]"; + }, + repeat(prefix) { + return String(prefix); + } +}; +var push_to_array = function(arr, value_or_array) { + Array.prototype.push.apply(arr, isArray(value_or_array) ? value_or_array : [value_or_array]); +}; +var toISOString; +var defaults = { + addQueryPrefix: false, + allowDots: false, + allowEmptyArrays: false, + arrayFormat: "indices", + charset: "utf-8", + charsetSentinel: false, + delimiter: "&", + encode: true, + encodeDotInKeys: false, + encoder: encode, + encodeValuesOnly: false, + format: default_format, + formatter: default_formatter, + /** @deprecated */ + indices: false, + serializeDate(date) { + return (toISOString ?? (toISOString = Function.prototype.call.bind(Date.prototype.toISOString)))(date); + }, + skipNulls: false, + strictNullHandling: false +}; +function is_non_nullish_primitive(v) { + return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint"; +} +var sentinel = {}; +function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { + let obj = object; + let tmp_sc = sideChannel; + let step = 0; + let find_flag = false; + while ((tmp_sc = tmp_sc.get(sentinel)) !== void 0 && !find_flag) { + const pos = tmp_sc.get(object); + step += 1; + if (typeof pos !== "undefined") { + if (pos === step) { + throw new RangeError("Cyclic object value"); + } else { + find_flag = true; + } + } + if (typeof tmp_sc.get(sentinel) === "undefined") { + step = 0; + } + } + if (typeof filter === "function") { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate?.(obj); + } else if (generateArrayPrefix === "comma" && isArray(obj)) { + obj = maybe_map(obj, function(value) { + if (value instanceof Date) { + return serializeDate?.(value); + } + return value; + }); + } + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? ( + // @ts-expect-error + encoder(prefix, defaults.encoder, charset, "key", format) + ) : prefix; + } + obj = ""; + } + if (is_non_nullish_primitive(obj) || is_buffer(obj)) { + if (encoder) { + const key_value = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, "key", format); + return [ + formatter?.(key_value) + "=" + // @ts-expect-error + formatter?.(encoder(obj, defaults.encoder, charset, "value", format)) + ]; + } + return [formatter?.(prefix) + "=" + formatter?.(String(obj))]; + } + const values = []; + if (typeof obj === "undefined") { + return values; + } + let obj_keys; + if (generateArrayPrefix === "comma" && isArray(obj)) { + if (encodeValuesOnly && encoder) { + obj = maybe_map(obj, encoder); + } + obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; + } else if (isArray(filter)) { + obj_keys = filter; + } else { + const keys = Object.keys(obj); + obj_keys = sort ? keys.sort(sort) : keys; + } + const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix); + const adjusted_prefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix; + if (allowEmptyArrays && isArray(obj) && obj.length === 0) { + return adjusted_prefix + "[]"; + } + for (let j = 0; j < obj_keys.length; ++j) { + const key = obj_keys[j]; + const value = ( + // @ts-ignore + typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key] + ); + if (skipNulls && value === null) { + continue; + } + const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key; + const key_prefix = isArray(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]"); + sideChannel.set(object, step); + const valueSideChannel = /* @__PURE__ */ new WeakMap(); + valueSideChannel.set(sentinel, sideChannel); + push_to_array(values, inner_stringify( + value, + key_prefix, + generateArrayPrefix, + commaRoundTrip, + allowEmptyArrays, + strictNullHandling, + skipNulls, + encodeDotInKeys, + // @ts-ignore + generateArrayPrefix === "comma" && encodeValuesOnly && isArray(obj) ? null : encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + valueSideChannel + )); + } + return values; +} +function normalize_stringify_options(opts = defaults) { + if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") { + throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); + } + if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") { + throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided"); + } + if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") { + throw new TypeError("Encoder has to be a function."); + } + const charset = opts.charset || defaults.charset; + if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { + throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); + } + let format = default_format; + if (typeof opts.format !== "undefined") { + if (!has(formatters, opts.format)) { + throw new TypeError("Unknown format option provided."); + } + format = opts.format; + } + const formatter = formatters[format]; + let filter = defaults.filter; + if (typeof opts.filter === "function" || isArray(opts.filter)) { + filter = opts.filter; + } + let arrayFormat; + if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) { + arrayFormat = opts.arrayFormat; + } else if ("indices" in opts) { + arrayFormat = opts.indices ? "indices" : "repeat"; + } else { + arrayFormat = defaults.arrayFormat; + } + if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") { + throw new TypeError("`commaRoundTrip` must be a boolean, or absent"); + } + const allowDots = typeof opts.allowDots === "undefined" ? !!opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; + return { + addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix, + // @ts-ignore + allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, + arrayFormat, + charset, + charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel, + commaRoundTrip: !!opts.commaRoundTrip, + delimiter: typeof opts.delimiter === "undefined" ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === "boolean" ? opts.encode : defaults.encode, + encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults.encodeDotInKeys, + encoder: typeof opts.encoder === "function" ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter, + format, + formatter, + serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults.skipNulls, + // @ts-ignore + sort: typeof opts.sort === "function" ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling + }; +} +function stringify(object, opts = {}) { + let obj = object; + const options = normalize_stringify_options(opts); + let obj_keys; + let filter; + if (typeof options.filter === "function") { + filter = options.filter; + obj = filter("", obj); + } else if (isArray(options.filter)) { + filter = options.filter; + obj_keys = filter; + } + const keys = []; + if (typeof obj !== "object" || obj === null) { + return ""; + } + const generateArrayPrefix = array_prefix_generators[options.arrayFormat]; + const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip; + if (!obj_keys) { + obj_keys = Object.keys(obj); + } + if (options.sort) { + obj_keys.sort(options.sort); + } + const sideChannel = /* @__PURE__ */ new WeakMap(); + for (let i = 0; i < obj_keys.length; ++i) { + const key = obj_keys[i]; + if (options.skipNulls && obj[key] === null) { + continue; + } + push_to_array(keys, inner_stringify( + obj[key], + key, + // @ts-expect-error + generateArrayPrefix, + commaRoundTrip, + options.allowEmptyArrays, + options.strictNullHandling, + options.skipNulls, + options.encodeDotInKeys, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.format, + options.formatter, + options.encodeValuesOnly, + options.charset, + sideChannel + )); + } + const joined = keys.join(options.delimiter); + let prefix = options.addQueryPrefix === true ? "?" : ""; + if (options.charsetSentinel) { + if (options.charset === "iso-8859-1") { + prefix += "utf8=%26%2310003%3B&"; + } else { + prefix += "utf8=%E2%9C%93&"; + } + } + return joined.length > 0 ? prefix + joined : ""; +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/query.mjs +function stringifyQuery(query) { + return stringify(query, { arrayFormat: "comma" }); +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/log.mjs +var levelNumbers = { + off: 0, + error: 200, + warn: 300, + info: 400, + debug: 500 +}; +var parseLogLevel = (maybeLevel, sourceName, client) => { + if (!maybeLevel) { + return void 0; + } + if (hasOwn(levelNumbers, maybeLevel)) { + return maybeLevel; + } + loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`); + return void 0; +}; +function noop() { +} +function makeLogFn(fnLevel, logger2, logLevel) { + if (!logger2 || levelNumbers[fnLevel] > levelNumbers[logLevel]) { + return noop; + } else { + return logger2[fnLevel].bind(logger2); + } +} +var noopLogger = { + error: noop, + warn: noop, + info: noop, + debug: noop +}; +var cachedLoggers = /* @__PURE__ */ new WeakMap(); +function loggerFor(client) { + const logger2 = client.logger; + const logLevel = client.logLevel ?? "off"; + if (!logger2) { + return noopLogger; + } + const cachedLogger = cachedLoggers.get(logger2); + if (cachedLogger && cachedLogger[0] === logLevel) { + return cachedLogger[1]; + } + const levelLogger = { + error: makeLogFn("error", logger2, logLevel), + warn: makeLogFn("warn", logger2, logLevel), + info: makeLogFn("info", logger2, logLevel), + debug: makeLogFn("debug", logger2, logLevel) + }; + cachedLoggers.set(logger2, [logLevel, levelLogger]); + return levelLogger; +} +var formatRequestDetails = (details) => { + if (details.options) { + details.options = { ...details.options }; + delete details.options["headers"]; + } + if (details.headers) { + details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ + name, + name.toLowerCase() === "authorization" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value + ])); + } + if ("retryOfRequestLogID" in details) { + if (details.retryOfRequestLogID) { + details.retryOf = details.retryOfRequestLogID; + } + delete details.retryOfRequestLogID; + } + return details; +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/parse.mjs +async function defaultParseResponse(client, props) { + const { response, requestLogID, retryOfRequestLogID, startTime } = props; + const body = await (async () => { + if (response.status === 204) { + return null; + } + if (props.options.__binaryResponse) { + return response; + } + const contentType = response.headers.get("content-type"); + const mediaType = contentType?.split(";")[0]?.trim(); + const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json"); + if (isJSON) { + const contentLength = response.headers.get("content-length"); + if (contentLength === "0") { + return void 0; + } + const json = await response.json(); + return json; + } + const text = await response.text(); + return text; + })(); + loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + body, + durationMs: Date.now() - startTime + })); + return body; +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/core/api-promise.mjs +var _APIPromise_client; +var APIPromise = class _APIPromise extends Promise { + constructor(client, responsePromise, parseResponse = defaultParseResponse) { + super((resolve) => { + resolve(null); + }); + this.responsePromise = responsePromise; + this.parseResponse = parseResponse; + _APIPromise_client.set(this, void 0); + __classPrivateFieldSet(this, _APIPromise_client, client, "f"); + } + _thenUnwrap(transform) { + return new _APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => transform(await this.parseResponse(client, props), props)); + } + /** + * Gets the raw `Response` instance instead of parsing the response + * data. + * + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + asResponse() { + return this.responsePromise.then((p) => p.response); + } + /** + * Gets the parsed response data and the raw `Response` instance. + * + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + async withResponse() { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { data, response }; + } + parse() { + if (!this.parsedPromise) { + this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data)); + } + return this.parsedPromise; + } + then(onfulfilled, onrejected) { + return this.parse().then(onfulfilled, onrejected); + } + catch(onrejected) { + return this.parse().catch(onrejected); + } + finally(onfinally) { + return this.parse().finally(onfinally); + } +}; +_APIPromise_client = /* @__PURE__ */ new WeakMap(); + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/core/pagination.mjs +var _AbstractPage_client; +var AbstractPage = class { + constructor(client, response, body, options) { + _AbstractPage_client.set(this, void 0); + __classPrivateFieldSet(this, _AbstractPage_client, client, "f"); + this.options = options; + this.response = response; + this.body = body; + } + hasNextPage() { + const items = this.getPaginatedItems(); + if (!items.length) + return false; + return this.nextPageRequestOptions() != null; + } + async getNextPage() { + const nextOptions = this.nextPageRequestOptions(); + if (!nextOptions) { + throw new StainlessError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`."); + } + return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); + } + async *iterPages() { + let page = this; + yield page; + while (page.hasNextPage()) { + page = await page.getNextPage(); + yield page; + } + } + async *[(_AbstractPage_client = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() { + for await (const page of this.iterPages()) { + for (const item of page.getPaginatedItems()) { + yield item; + } + } + } +}; +var PagePromise = class extends APIPromise { + constructor(client, request, Page2) { + super(client, request, async (client2, props) => new Page2(client2, props.response, await defaultParseResponse(client2, props), props.options)); + } + /** + * Allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ + async *[Symbol.asyncIterator]() { + const page = await this; + for await (const item of page) { + yield item; + } + } +}; +var Page = class extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.next_cursor = body.next_cursor || ""; + } + getPaginatedItems() { + return this.data ?? []; + } + nextPageRequestOptions() { + const cursor = this.next_cursor; + if (!cursor) { + return null; + } + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + cursor + } + }; + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/uploads.mjs +var checkFileSupport = () => { + if (typeof File === "undefined") { + const { process: process7 } = globalThis; + const isOldNode = typeof process7?.versions?.node === "string" && parseInt(process7.versions.node.split(".")) < 20; + throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : "")); + } +}; +function makeFile(fileBits, fileName, options) { + checkFileSupport(); + return new File(fileBits, fileName ?? "unknown_file", options); +} +function getName(value) { + return (typeof value === "object" && value !== null && ("name" in value && value.name && String(value.name) || "url" in value && value.url && String(value.url) || "filename" in value && value.filename && String(value.filename) || "path" in value && value.path && String(value.path)) || "").split(/[\\/]/).pop() || void 0; +} +var isAsyncIterable = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function"; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/to-file.mjs +var isBlobLike = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function"; +var isFileLike = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value); +var isResponseLike = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function"; +async function toFile(value, name, options) { + checkFileSupport(); + value = await value; + if (isFileLike(value)) { + if (value instanceof File) { + return value; + } + return makeFile([await value.arrayBuffer()], value.name); + } + if (isResponseLike(value)) { + const blob = await value.blob(); + name || (name = new URL(value.url).pathname.split(/[\\/]/).pop()); + return makeFile(await getBytes(blob), name, options); + } + const parts = await getBytes(value); + name || (name = getName(value)); + if (!options?.type) { + const type = parts.find((part) => typeof part === "object" && "type" in part && part.type); + if (typeof type === "string") { + options = { ...options, type }; + } + } + return makeFile(parts, name, options); +} +async function getBytes(value) { + let parts = []; + if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. + value instanceof ArrayBuffer) { + parts.push(value); + } else if (isBlobLike(value)) { + parts.push(value instanceof Blob ? value : await value.arrayBuffer()); + } else if (isAsyncIterable(value)) { + for await (const chunk of value) { + parts.push(...await getBytes(chunk)); + } + } else { + const constructor = value?.constructor?.name; + throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError(value)}`); + } + return parts; +} +function propsForError(value) { + if (typeof value !== "object" || value === null) + return ""; + const props = Object.getOwnPropertyNames(value); + return `; props: [${props.map((p) => `"${p}"`).join(", ")}]`; +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/core/resource.mjs +var APIResource = class { + constructor(client) { + this._client = client; + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/path.mjs +function encodeURIPath(str) { + return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); +} +var EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); +var createPathTagFunction = (pathEncoder = encodeURIPath) => function path7(statics, ...params) { + if (statics.length === 1) + return statics[0]; + let postPath = false; + const invalidSegments = []; + const path8 = statics.reduce((previousValue, currentValue, index) => { + if (/[?#]/.test(currentValue)) { + postPath = true; + } + const value = params[index]; + let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value); + if (index !== params.length && (value == null || typeof value === "object" && // handle values from other realms + value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY)?.toString)) { + encoded = value + ""; + invalidSegments.push({ + start: previousValue.length + currentValue.length, + length: encoded.length, + error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter` + }); + } + return previousValue + currentValue + (index === params.length ? "" : encoded); + }, ""); + const pathOnly = path8.split(/[?#]/, 1)[0]; + const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; + let match; + while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) { + invalidSegments.push({ + start: match.index, + length: match[0].length, + error: `Value "${match[0]}" can't be safely passed as a path parameter` + }); + } + invalidSegments.sort((a, b) => a.start - b.start); + if (invalidSegments.length > 0) { + let lastEnd = 0; + const underline = invalidSegments.reduce((acc, segment) => { + const spaces = " ".repeat(segment.start - lastEnd); + const arrows = "^".repeat(segment.length); + lastEnd = segment.start + segment.length; + return acc + spaces + arrows; + }, ""); + throw new StainlessError(`Path parameters result in path with invalid segments: +${invalidSegments.map((e) => e.error).join("\n")} +${path8} +${underline}`); + } + return path8; +}; +var path3 = /* @__PURE__ */ createPathTagFunction(encodeURIPath); + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/builds/diagnostics.mjs +var Diagnostics = class extends APIResource { + /** + * Get the list of diagnostics for a given build. + * + * If no language targets are specified, diagnostics for all languages are + * returned. + */ + list(buildID, query = {}, options) { + return this._client.getAPIList(path3`/v0/builds/${buildID}/diagnostics`, Page, { + query, + ...options + }); + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/builds/target-outputs.mjs +var TargetOutputs = class extends APIResource { + /** + * Retrieve a method to download an output for a given build target. + * + * If the requested type of output is `source`, and the requested output method is + * `url`, a download link to a tarball of the source files is returned. If the + * requested output method is `git`, a Git remote, ref, and access token (if + * necessary) is returned. + * + * Otherwise, the possible types of outputs are specific to the requested target, + * and the output method _must_ be `url`. See the documentation for `type` for more + * information. + */ + retrieve(query, options) { + return this._client.get("/v0/build_target_outputs", { query, ...options }); + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/builds/builds.mjs +var Builds = class extends APIResource { + constructor() { + super(...arguments); + this.diagnostics = new Diagnostics(this._client); + this.targetOutputs = new TargetOutputs(this._client); + } + /** + * Create a build, on top of a project branch, against a given input revision. + * + * The project branch will be modified so that its latest set of config files + * points to the one specified by the input revision. + */ + create(params, options) { + const { project = this._client.project, ...body } = params; + return this._client.post("/v0/builds", { body: { project, ...body }, ...options }); + } + /** + * Retrieve a build by its ID. + */ + retrieve(buildID, options) { + return this._client.get(path3`/v0/builds/${buildID}`, options); + } + /** + * List user-triggered builds for a given project. + * + * An optional revision can be specified to filter by config commit SHA, or hashes + * of file contents. + */ + list(params = {}, options) { + const { project = this._client.project, ...query } = params ?? {}; + return this._client.getAPIList("/v0/builds", Page, { query: { project, ...query }, ...options }); + } + /** + * Create two builds whose outputs can be directly compared with each other. + * + * Created builds _modify_ their project branches so that their latest sets of + * config files point to the ones specified by the input revision. + * + * This endpoint is useful because a build has more inputs than the set of config + * files it uses, so comparing two builds directly may return spurious differences. + * Builds made via this endpoint are guaranteed to have differences arising from + * the set of config files, and any custom code. + */ + compare(params, options) { + const { project = this._client.project, ...body } = params; + return this._client.post("/v0/builds/compare", { body: { project, ...body }, ...options }); + } +}; +Builds.Diagnostics = Diagnostics; +Builds.TargetOutputs = TargetOutputs; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/orgs.mjs +var Orgs = class extends APIResource { + /** + * Retrieve an organization by name. + */ + retrieve(org, options) { + return this._client.get(path3`/v0/orgs/${org}`, options); + } + /** + * List organizations accessible to the current authentication method. + */ + list(options) { + return this._client.get("/v0/orgs", options); + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/projects/branches.mjs +var Branches = class extends APIResource { + /** + * Create a new branch for a project. + * + * The branch inherits the config files from the revision pointed to by the + * `branch_from` parameter. In addition, if the revision is a branch name, the + * branch will also inherit custom code changes from that branch. + */ + create(params, options) { + const { project = this._client.project, ...body } = params; + return this._client.post(path3`/v0/projects/${project}/branches`, { body, ...options }); + } + /** + * Retrieve a project branch by name. + */ + retrieve(branch, params = {}, options) { + const { project = this._client.project } = params ?? {}; + return this._client.get(path3`/v0/projects/${project}/branches/${branch}`, options); + } + /** + * Retrieve a project branch by name. + */ + list(params = {}, options) { + const { project = this._client.project, ...query } = params ?? {}; + return this._client.getAPIList(path3`/v0/projects/${project}/branches`, Page, { + query, + ...options + }); + } + /** + * Delete a project branch by name. + */ + delete(branch, params = {}, options) { + const { project = this._client.project } = params ?? {}; + return this._client.delete(path3`/v0/projects/${project}/branches/${branch}`, options); + } + /** + * Rebase a project branch. + * + * The branch is rebased onto the `base` branch or commit SHA, inheriting any + * config and custom code changes. + */ + rebase(branch, params = {}, options) { + const { project = this._client.project, base } = params ?? {}; + return this._client.put(path3`/v0/projects/${project}/branches/${branch}/rebase`, { + query: { base }, + ...options + }); + } + /** + * Reset a project branch. + * + * If `branch` === `main`, the branch is reset to `target_config_sha`. Otherwise, + * the branch is reset to `main`. + */ + reset(branch, params = {}, options) { + const { project = this._client.project, target_config_sha } = params ?? {}; + return this._client.put(path3`/v0/projects/${project}/branches/${branch}/reset`, { + query: { target_config_sha }, + ...options + }); + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/projects/configs.mjs +var Configs = class extends APIResource { + /** + * Retrieve the configuration files for a given project. + */ + retrieve(params = {}, options) { + const { project = this._client.project, ...query } = params ?? {}; + return this._client.get(path3`/v0/projects/${project}/configs`, { query, ...options }); + } + /** + * Generate suggestions for changes to config files based on an OpenAPI spec. + */ + guess(params, options) { + const { project = this._client.project, ...body } = params; + return this._client.post(path3`/v0/projects/${project}/configs/guess`, { body, ...options }); + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/projects/projects.mjs +var Projects = class extends APIResource { + constructor() { + super(...arguments); + this.branches = new Branches(this._client); + this.configs = new Configs(this._client); + } + /** + * Create a new project. + */ + create(body, options) { + return this._client.post("/v0/projects", { body, ...options }); + } + /** + * Retrieve a project by name. + */ + retrieve(params = {}, options) { + const { project = this._client.project } = params ?? {}; + return this._client.get(path3`/v0/projects/${project}`, options); + } + /** + * Update a project's properties. + */ + update(params = {}, options) { + const { project = this._client.project, ...body } = params ?? {}; + return this._client.patch(path3`/v0/projects/${project}`, { body, ...options }); + } + /** + * List projects in an organization, from oldest to newest. + */ + list(query = {}, options) { + return this._client.getAPIList("/v0/projects", Page, { query, ...options }); + } + /** + * Generates an AI commit message by comparing two git refs in the SDK repository. + */ + generateCommitMessage(params, options) { + const { project = this._client.project, target, ...body } = params; + return this._client.post(path3`/v0/projects/${project}/generate_commit_message`, { + query: { target }, + body, + ...options + }); + } +}; +Projects.Branches = Branches; +Projects.Configs = Configs; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/user.mjs +var User = class extends APIResource { + /** + * Retrieve the currently authenticated user's information. + */ + retrieve(options) { + return this._client.get("/v0/user", options); + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/headers.mjs +var brand_privateNullableHeaders = /* @__PURE__ */ Symbol("brand.privateNullableHeaders"); +function* iterateHeaders(headers) { + if (!headers) + return; + if (brand_privateNullableHeaders in headers) { + const { values, nulls } = headers; + yield* values.entries(); + for (const name of nulls) { + yield [name, null]; + } + return; + } + let shouldClear = false; + let iter; + if (headers instanceof Headers) { + iter = headers.entries(); + } else if (isReadonlyArray(headers)) { + iter = headers; + } else { + shouldClear = true; + iter = Object.entries(headers ?? {}); + } + for (let row of iter) { + const name = row[0]; + if (typeof name !== "string") + throw new TypeError("expected header name to be a string"); + const values = isReadonlyArray(row[1]) ? row[1] : [row[1]]; + let didClear = false; + for (const value of values) { + if (value === void 0) + continue; + if (shouldClear && !didClear) { + didClear = true; + yield [name, null]; + } + yield [name, value]; + } + } +} +var buildHeaders = (newHeaders) => { + const targetHeaders = new Headers(); + const nullHeaders = /* @__PURE__ */ new Set(); + for (const headers of newHeaders) { + const seenHeaders = /* @__PURE__ */ new Set(); + for (const [name, value] of iterateHeaders(headers)) { + const lowerName = name.toLowerCase(); + if (!seenHeaders.has(lowerName)) { + targetHeaders.delete(name); + seenHeaders.add(lowerName); + } + if (value === null) { + targetHeaders.delete(name); + nullHeaders.add(lowerName); + } else { + targetHeaders.append(name, value); + nullHeaders.delete(lowerName); + } + } + } + return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders }; +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/env.mjs +var readEnv = (env) => { + if (typeof globalThis.process !== "undefined") { + return globalThis.process.env?.[env]?.trim() ?? void 0; + } + if (typeof globalThis.Deno !== "undefined") { + return globalThis.Deno.env?.get?.(env)?.trim(); + } + return void 0; +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/lib/unwrap.mjs +async function unwrapFile(value) { + if (value === null) { + return null; + } + if (value.type === "content") { + return value.content; + } + const response = await fetch(value.url); + return response.text(); +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/client.mjs +var _Stainless_instances; +var _a; +var _Stainless_encoder; +var _Stainless_baseURLOverridden; +var environments = { + production: "https://api.stainless.com", + staging: "https://staging.stainless.com" +}; +var Stainless = class { + /** + * API Client for interfacing with the Stainless API. + * + * @param {string | null | undefined} [opts.apiKey=process.env['STAINLESS_API_KEY'] ?? null] + * @param {string | null | undefined} [opts.project] + * @param {Environment} [opts.environment=production] - Specifies the environment URL to use for the API. + * @param {string} [opts.baseURL=process.env['STAINLESS_BASE_URL'] ?? https://api.stainless.com] - Override the default base URL for the API. + * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. + * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. + */ + constructor({ baseURL = readEnv("STAINLESS_BASE_URL"), apiKey = readEnv("STAINLESS_API_KEY") ?? null, project = null, ...opts } = {}) { + _Stainless_instances.add(this); + _Stainless_encoder.set(this, void 0); + this.projects = new Projects(this); + this.builds = new Builds(this); + this.orgs = new Orgs(this); + this.user = new User(this); + const options = { + apiKey, + project, + ...opts, + baseURL, + environment: opts.environment ?? "production" + }; + if (baseURL && opts.environment) { + throw new StainlessError("Ambiguous URL; The `baseURL` option (or STAINLESS_BASE_URL env var) and the `environment` option are given. If you want to use the environment you must pass baseURL: null"); + } + this.baseURL = options.baseURL || environments[options.environment || "production"]; + this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT; + this.logger = options.logger ?? console; + const defaultLogLevel = "warn"; + this.logLevel = defaultLogLevel; + this.logLevel = parseLogLevel(options.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel(readEnv("STAINLESS_LOG"), "process.env['STAINLESS_LOG']", this) ?? defaultLogLevel; + this.fetchOptions = options.fetchOptions; + this.maxRetries = options.maxRetries ?? 2; + this.fetch = options.fetch ?? getDefaultFetch(); + __classPrivateFieldSet(this, _Stainless_encoder, FallbackEncoder, "f"); + this._options = options; + this.apiKey = apiKey; + this.project = project; + } + /** + * Create a new client instance re-using the same options given to the current client with optional overriding. + */ + withOptions(options) { + const client = new this.constructor({ + ...this._options, + environment: options.environment ? options.environment : void 0, + baseURL: options.environment ? void 0 : this.baseURL, + maxRetries: this.maxRetries, + timeout: this.timeout, + logger: this.logger, + logLevel: this.logLevel, + fetch: this.fetch, + fetchOptions: this.fetchOptions, + apiKey: this.apiKey, + project: this.project, + ...options + }); + return client; + } + defaultQuery() { + return this._options.defaultQuery; + } + validateHeaders({ values, nulls }) { + if (this.apiKey && values.get("authorization")) { + return; + } + if (nulls.has("authorization")) { + return; + } + throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "Authorization" headers to be explicitly omitted'); + } + async authHeaders(opts) { + if (this.apiKey == null) { + return void 0; + } + return buildHeaders([{ Authorization: `Bearer ${this.apiKey}` }]); + } + stringifyQuery(query) { + return stringifyQuery(query); + } + getUserAgent() { + return `${this.constructor.name}/JS ${VERSION}`; + } + defaultIdempotencyKey() { + return `stainless-node-retry-${uuid4()}`; + } + makeStatusError(status, error, message, headers) { + return APIError.generate(status, error, message, headers); + } + buildURL(path7, query, defaultBaseURL) { + const baseURL = !__classPrivateFieldGet(this, _Stainless_instances, "m", _Stainless_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL; + const url = isAbsoluteURL(path7) ? new URL(path7) : new URL(baseURL + (baseURL.endsWith("/") && path7.startsWith("/") ? path7.slice(1) : path7)); + const defaultQuery = this.defaultQuery(); + if (!isEmptyObj(defaultQuery)) { + query = { ...defaultQuery, ...query }; + } + if (typeof query === "object" && query && !Array.isArray(query)) { + url.search = this.stringifyQuery(query); + } + return url.toString(); + } + /** + * Used as a callback for mutating the given `FinalRequestOptions` object. + */ + async prepareOptions(options) { + } + /** + * Used as a callback for mutating the given `RequestInit` object. + * + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. + */ + async prepareRequest(request, { url, options }) { + } + get(path7, opts) { + return this.methodRequest("get", path7, opts); + } + post(path7, opts) { + return this.methodRequest("post", path7, opts); + } + patch(path7, opts) { + return this.methodRequest("patch", path7, opts); + } + put(path7, opts) { + return this.methodRequest("put", path7, opts); + } + delete(path7, opts) { + return this.methodRequest("delete", path7, opts); + } + methodRequest(method, path7, opts) { + return this.request(Promise.resolve(opts).then((opts2) => { + return { method, path: path7, ...opts2 }; + })); + } + request(options, remainingRetries = null) { + return new APIPromise(this, this.makeRequest(options, remainingRetries, void 0)); + } + async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { + const options = await optionsInput; + const maxRetries = options.maxRetries ?? this.maxRetries; + if (retriesRemaining == null) { + retriesRemaining = maxRetries; + } + await this.prepareOptions(options); + const { req, url, timeout } = await this.buildRequest(options, { + retryCount: maxRetries - retriesRemaining + }); + await this.prepareRequest(req, { url, options }); + const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0"); + const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`; + const startTime = Date.now(); + loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({ + retryOfRequestLogID, + method: options.method, + url, + options, + headers: req.headers + })); + if (options.signal?.aborted) { + throw new APIUserAbortError(); + } + const controller = new AbortController(); + const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError); + const headersTime = Date.now(); + if (response instanceof globalThis.Error) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + if (options.signal?.aborted) { + throw new APIUserAbortError(); + } + const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : "")); + if (retriesRemaining) { + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`); + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); + } + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`); + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + if (isTimeout) { + throw new APIConnectionTimeoutError(); + } + throw new APIConnectionError({ cause: response }); + } + const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`; + if (!response.ok) { + const shouldRetry = await this.shouldRetry(response); + if (retriesRemaining && shouldRetry) { + const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`; + await CancelReadableStream(response.body); + loggerFor(this).info(`${responseInfo} - ${retryMessage2}`); + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); + } + const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; + loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + const errText = await response.text().catch((err2) => castToError(err2).message); + const errJSON = safeJSON(errText); + const errMessage = errJSON ? void 0 : errText; + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + message: errMessage, + durationMs: Date.now() - startTime + })); + const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); + throw err; + } + loggerFor(this).info(responseInfo); + loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; + } + getAPIList(path7, Page2, opts) { + return this.requestAPIList(Page2, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path7, ...opts2 })) : { method: "get", path: path7, ...opts }); + } + requestAPIList(Page2, options) { + const request = this.makeRequest(options, null, void 0); + return new PagePromise(this, request, Page2); + } + async fetchWithTimeout(url, init, ms, controller) { + const { signal, method, ...options } = init || {}; + const abort = this._makeAbort(controller); + if (signal) + signal.addEventListener("abort", abort, { once: true }); + const timeout = setTimeout(abort, ms); + const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body; + const fetchOptions = { + signal: controller.signal, + ...isReadableBody ? { duplex: "half" } : {}, + method: "GET", + ...options + }; + if (method) { + fetchOptions.method = method.toUpperCase(); + } + try { + return await this.fetch.call(void 0, url, fetchOptions); + } finally { + clearTimeout(timeout); + } + } + async shouldRetry(response) { + const shouldRetryHeader = response.headers.get("x-should-retry"); + if (shouldRetryHeader === "true") + return true; + if (shouldRetryHeader === "false") + return false; + if (response.status === 408) + return true; + if (response.status === 409) + return true; + if (response.status === 429) + return true; + if (response.status >= 500) + return true; + return false; + } + async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { + let timeoutMillis; + const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms"); + if (retryAfterMillisHeader) { + const timeoutMs = parseFloat(retryAfterMillisHeader); + if (!Number.isNaN(timeoutMs)) { + timeoutMillis = timeoutMs; + } + } + const retryAfterHeader = responseHeaders?.get("retry-after"); + if (retryAfterHeader && !timeoutMillis) { + const timeoutSeconds = parseFloat(retryAfterHeader); + if (!Number.isNaN(timeoutSeconds)) { + timeoutMillis = timeoutSeconds * 1e3; + } else { + timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); + } + } + if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1e3)) { + const maxRetries = options.maxRetries ?? this.maxRetries; + timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + } + await sleep(timeoutMillis); + return this.makeRequest(options, retriesRemaining - 1, requestLogID); + } + calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { + const initialRetryDelay = 0.5; + const maxRetryDelay = 8; + const numRetries = maxRetries - retriesRemaining; + const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); + const jitter = 1 - Math.random() * 0.25; + return sleepSeconds * jitter * 1e3; + } + async buildRequest(inputOptions, { retryCount = 0 } = {}) { + const options = { ...inputOptions }; + const { method, path: path7, query, defaultBaseURL } = options; + const url = this.buildURL(path7, query, defaultBaseURL); + if ("timeout" in options) + validatePositiveInteger("timeout", options.timeout); + options.timeout = options.timeout ?? this.timeout; + const { bodyHeaders, body } = this.buildBody({ options }); + const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); + const req = { + method, + headers: reqHeaders, + ...options.signal && { signal: options.signal }, + ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" }, + ...body && { body }, + ...this.fetchOptions ?? {}, + ...options.fetchOptions ?? {} + }; + return { req, url, timeout: options.timeout }; + } + async buildHeaders({ options, method, bodyHeaders, retryCount }) { + let idempotencyHeaders = {}; + if (this.idempotencyHeader && method !== "get") { + if (!options.idempotencyKey) + options.idempotencyKey = this.defaultIdempotencyKey(); + idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; + } + const headers = buildHeaders([ + idempotencyHeaders, + { + Accept: "application/json", + "User-Agent": this.getUserAgent(), + "X-Stainless-Retry-Count": String(retryCount), + ...options.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options.timeout / 1e3)) } : {}, + ...getPlatformHeaders() + }, + await this.authHeaders(options), + this._options.defaultHeaders, + bodyHeaders, + options.headers + ]); + this.validateHeaders(headers); + return headers.values; + } + _makeAbort(controller) { + return () => controller.abort(); + } + buildBody({ options: { body, headers: rawHeaders } }) { + if (!body) { + return { bodyHeaders: void 0, body: void 0 }; + } + const headers = buildHeaders([rawHeaders]); + if ( + // Pass raw type verbatim + ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && // Preserve legacy string encoding behavior for now + headers.values.has("content-type") || // `Blob` is superset of `File` + globalThis.Blob && body instanceof globalThis.Blob || // `FormData` -> `multipart/form-data` + body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded` + body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`) + globalThis.ReadableStream && body instanceof globalThis.ReadableStream + ) { + return { bodyHeaders: void 0, body }; + } else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) { + return { bodyHeaders: void 0, body: ReadableStreamFrom(body) }; + } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") { + return { + bodyHeaders: { "content-type": "application/x-www-form-urlencoded" }, + body: this.stringifyQuery(body) + }; + } else { + return __classPrivateFieldGet(this, _Stainless_encoder, "f").call(this, { body, headers }); + } + } +}; +_a = Stainless, _Stainless_encoder = /* @__PURE__ */ new WeakMap(), _Stainless_instances = /* @__PURE__ */ new WeakSet(), _Stainless_baseURLOverridden = function _Stainless_baseURLOverridden2() { + return this.baseURL !== environments[this._options.environment || "production"]; +}; +Stainless.Stainless = _a; +Stainless.DEFAULT_TIMEOUT = 6e4; +Stainless.StainlessError = StainlessError; +Stainless.APIError = APIError; +Stainless.APIConnectionError = APIConnectionError; +Stainless.APIConnectionTimeoutError = APIConnectionTimeoutError; +Stainless.APIUserAbortError = APIUserAbortError; +Stainless.NotFoundError = NotFoundError; +Stainless.ConflictError = ConflictError; +Stainless.RateLimitError = RateLimitError; +Stainless.BadRequestError = BadRequestError; +Stainless.AuthenticationError = AuthenticationError; +Stainless.InternalServerError = InternalServerError; +Stainless.PermissionDeniedError = PermissionDeniedError; +Stainless.UnprocessableEntityError = UnprocessableEntityError; +Stainless.toFile = toFile; +Stainless.unwrapFile = unwrapFile; +Stainless.Projects = Projects; +Stainless.Builds = Builds; +Stainless.Orgs = Orgs; +Stainless.User = User; + +// src/error.ts +var ActionError = class extends Error { + constructor(message, options) { + super(message, options); + this.name = "ActionError"; + } +}; + // src/logger.ts var LOG_LEVELS = { debug: 0, @@ -9560,11 +11453,14 @@ function createLoggerImpl(logContext) { error: errorFn, fatal(message, ...args) { errorFn(message, ...args); - process.stderr.write( - ` + const isActionError = args.some((arg) => arg instanceof ActionError); + if (!isActionError) { + process.stderr.write( + ` This is a bug. Please report it at ${BUG_REPORT_URL} ` - ); + ); + } }, child(childContext) { const { context, ...rest } = logContext; @@ -9751,11 +11647,11 @@ Make sure: ); } if (!outputPath) { - const inputDir = path5.dirname(inputPath); - outputPath = path5.join(inputDir, "openapi.json"); + const inputDir = path6.dirname(inputPath); + outputPath = path6.join(inputDir, "openapi.json"); logger.info(`Output path not specified, using: ${outputPath}`); } - const outputDir = path5.dirname(outputPath); + const outputDir = path6.dirname(outputPath); if (!fs3.existsSync(outputDir)) { fs3.mkdirSync(outputDir, { recursive: true }); } diff --git a/dist/preview.js b/dist/preview.js index deafc41..f701fbc 100644 --- a/dist/preview.js +++ b/dist/preview.js @@ -9243,135 +9243,37 @@ function logging() { return cachedLogging; } -// src/logger.ts -var LOG_LEVELS = { - debug: 0, - info: 1, - warn: 2, - error: 3, - off: 4 -}; -var COLORS2 = { - reset: "\x1B[0m", - bold: "\x1B[1m", - dim: "\x1B[90m", - cyan: "\x1B[36m", - green: "\x1B[32m", - yellow: "\x1B[33m", - red: "\x1B[31m", - magenta: "\x1B[35m" -}; -var LEVEL_COLORS = { - debug: COLORS2.cyan, - info: COLORS2.green, - warn: COLORS2.yellow, - error: COLORS2.red -}; -var LEVEL_LABELS = { - debug: "DEBUG", - info: "INFO", - warn: "WARN", - error: "ERROR" -}; -var LABEL_WIDTH = 5; -var LOG_LEVEL_CHOICES = ["debug", "info", "warn", "error", "off"]; -function formatTimestamp() { - const now = /* @__PURE__ */ new Date(); - const pad = (n, len = 2) => n.toString().padStart(len, "0"); - return `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}.${pad(now.getMilliseconds(), 3)}`; +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/tslib.mjs +function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") + throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; } -function formatArgs(args) { - if (args.length === 0) return ""; - return args.map((arg) => { - if (arg === null) return "null"; - if (arg === void 0) return "undefined"; - if (typeof arg === "string") return arg; - if (arg instanceof Error) return arg.stack || arg.message; - try { - return JSON.stringify(arg, null, 2); - } catch { - return String(arg); - } - }).join(" "); +function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); } -function createLogFn(level, { context, minLevel, provider }) { - if (LOG_LEVELS[level] < minLevel) { - return () => { - }; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/uuid.mjs +var uuid4 = function() { + const { crypto: crypto2 } = globalThis; + if (crypto2?.randomUUID) { + uuid4 = crypto2.randomUUID.bind(crypto2); + return crypto2.randomUUID(); } - return (message, ...args) => { - const extra = formatArgs(args); - const line = [ - `${COLORS2.dim}${formatTimestamp()}${COLORS2.reset}`, - `${LEVEL_COLORS[level]}${COLORS2.bold}${LEVEL_LABELS[level].padEnd(LABEL_WIDTH)}${COLORS2.reset}`, - context ? `${COLORS2.magenta}[${context}]${COLORS2.reset}` : null, - message, - extra || null - ].filter(Boolean).join(" "); - const stream = level === "error" || level === "warn" ? process.stderr : process.stdout; - stream.write(line + "\n"); - if (level === "error") { - provider.emitErrorAnnotation(message + (extra ? " " + extra : "")); - } - }; -} -var BUG_REPORT_URL = "https://github.com/stainless-api/upload-openapi-spec-action/issues"; -function createLoggerImpl(logContext) { - const { provider } = logContext; - const errorFn = createLogFn("error", logContext); - const groupStack = []; - return { - debug: createLogFn("debug", logContext), - info: createLogFn("info", logContext), - warn: createLogFn("warn", logContext), - error: errorFn, - fatal(message, ...args) { - errorFn(message, ...args); - process.stderr.write( - ` -This is a bug. Please report it at ${BUG_REPORT_URL} -` - ); - }, - child(childContext) { - const { context, ...rest } = logContext; - const newContext = context ? `${context}:${childContext}` : childContext; - return createLoggerImpl({ context: newContext, ...rest }); - }, - group(name) { - const id = provider.startGroup(name); - groupStack.push(id); - }, - groupEnd() { - const id = groupStack.pop(); - if (id !== void 0) { - provider.endGroup(id); - } - }, - withGroup(name, fn) { - const id = provider.startGroup(name); - try { - const result = fn(); - if (result instanceof Promise) { - return result.finally(() => provider.endGroup(id)); - } - provider.endGroup(id); - return result; - } catch (e) { - provider.endGroup(id); - throw e; - } - } - }; -} -function createLogger(options = {}) { - const minLevel = LOG_LEVELS[options.level ?? getInput("log_level", { choices: LOG_LEVEL_CHOICES }) ?? "info"]; - const provider = logging(); - return createLoggerImpl({ minLevel, provider }); -} -var logger = createLogger(); + const u8 = new Uint8Array(1); + const randomByte = crypto2 ? () => crypto2.getRandomValues(u8)[0] : () => Math.random() * 255 & 255; + return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16)); +}; -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/errors.mjs +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/errors.mjs function isAbortError(err) { return typeof err === "object" && err !== null && // Spec-compliant fetch implementations ("name" in err && err.name === "AbortError" || // Expo fetch @@ -9402,13 +9304,10 @@ var castToError = (err) => { return new Error(err); }; -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/core/error.mjs -var GitHubError = /* @__PURE__ */ (() => { - class GitHubError2 extends Error { - } - return GitHubError2; -})(); -var APIError = class _APIError extends GitHubError { +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/core/error.mjs +var StainlessError = class extends Error { +}; +var APIError = class _APIError extends StainlessError { constructor(status, error, message, headers) { super(`${_APIError.makeMessage(status, error, message)}`); this.status = status; @@ -9494,36 +9393,7 @@ var RateLimitError = class extends APIError { var InternalServerError = class extends APIError { }; -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/core/resource.mjs -var APIResource = /* @__PURE__ */ (() => { - class APIResource4 { - constructor(client) { - this._client = client; - } - } - APIResource4._key = []; - return APIResource4; -})(); - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/tslib.mjs -function __classPrivateFieldSet(receiver, state, value, kind, f) { - if (kind === "m") - throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) - throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) - throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; -} -function __classPrivateFieldGet(receiver, state, kind, f) { - if (kind === "a" && !f) - throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) - throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -} - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/utils/values.mjs +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/values.mjs var startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; var isAbsoluteURL = (url) => { return startsWithSchemeRegexp.test(url); @@ -9548,10 +9418,10 @@ function hasOwn(obj, key) { } var validatePositiveInteger = (name, n) => { if (typeof n !== "number" || !Number.isInteger(n)) { - throw new GitHubError(`${name} must be an integer`); + throw new StainlessError(`${name} must be an integer`); } if (n < 0) { - throw new GitHubError(`${name} must be a positive integer`); + throw new StainlessError(`${name} must be a positive integer`); } return n; }; @@ -9563,3997 +9433,2659 @@ var safeJSON = (text) => { } }; -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/utils/log.mjs -var levelNumbers = { - off: 0, - error: 200, - warn: 300, - info: 400, - debug: 500 -}; -var parseLogLevel = (maybeLevel, sourceName, client) => { - if (!maybeLevel) { - return void 0; +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/sleep.mjs +var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/version.mjs +var VERSION = "0.5.0"; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/detect-platform.mjs +function getDetectedPlatform() { + if (typeof Deno !== "undefined" && Deno.build != null) { + return "deno"; } - if (hasOwn(levelNumbers, maybeLevel)) { - return maybeLevel; + if (typeof EdgeRuntime !== "undefined") { + return "edge"; } - loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`); - return void 0; -}; -function noop() { -} -function makeLogFn(fnLevel, logger2, logLevel) { - if (!logger2 || levelNumbers[fnLevel] > levelNumbers[logLevel]) { - return noop; - } else { - return logger2[fnLevel].bind(logger2); + if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") { + return "node"; } + return "unknown"; } -var noopLogger = { - error: noop, - warn: noop, - info: noop, - debug: noop -}; -var cachedLoggers = /* @__PURE__ */ new WeakMap(); -function loggerFor(client) { - const logger2 = client.logger; - const logLevel = client.logLevel ?? "off"; - if (!logger2) { - return noopLogger; +var getPlatformProperties = () => { + const detectedPlatform = getDetectedPlatform(); + if (detectedPlatform === "deno") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": normalizePlatform(Deno.build.os), + "X-Stainless-Arch": normalizeArch(Deno.build.arch), + "X-Stainless-Runtime": "deno", + "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown" + }; } - const cachedLogger = cachedLoggers.get(logger2); - if (cachedLogger && cachedLogger[0] === logLevel) { - return cachedLogger[1]; + if (typeof EdgeRuntime !== "undefined") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": `other:${EdgeRuntime}`, + "X-Stainless-Runtime": "edge", + "X-Stainless-Runtime-Version": globalThis.process.version + }; } - const levelLogger = { - error: makeLogFn("error", logger2, logLevel), - warn: makeLogFn("warn", logger2, logLevel), - info: makeLogFn("info", logger2, logLevel), - debug: makeLogFn("debug", logger2, logLevel) - }; - cachedLoggers.set(logger2, [logLevel, levelLogger]); - return levelLogger; -} -var formatRequestDetails = (details) => { - if (details.options) { - details.options = { ...details.options }; - delete details.options["headers"]; + if (detectedPlatform === "node") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": normalizePlatform(globalThis.process.platform ?? "unknown"), + "X-Stainless-Arch": normalizeArch(globalThis.process.arch ?? "unknown"), + "X-Stainless-Runtime": "node", + "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown" + }; } - if (details.headers) { - details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ - name, - name.toLowerCase() === "authorization" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value - ])); + const browserInfo = getBrowserInfo(); + if (browserInfo) { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": "unknown", + "X-Stainless-Runtime": `browser:${browserInfo.browser}`, + "X-Stainless-Runtime-Version": browserInfo.version + }; } - if ("retryOfRequestLogID" in details) { - if (details.retryOfRequestLogID) { - details.retryOf = details.retryOfRequestLogID; + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": "unknown", + "X-Stainless-Runtime": "unknown", + "X-Stainless-Runtime-Version": "unknown" + }; +}; +function getBrowserInfo() { + if (typeof navigator === "undefined" || !navigator) { + return null; + } + const browserPatterns = [ + { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ } + ]; + for (const { key, pattern } of browserPatterns) { + const match = pattern.exec(navigator.userAgent); + if (match) { + const major = match[1] || 0; + const minor = match[2] || 0; + const patch = match[3] || 0; + return { browser: key, version: `${major}.${minor}.${patch}` }; } - delete details.retryOfRequestLogID; } - return details; + return null; +} +var normalizeArch = (arch) => { + if (arch === "x32") + return "x32"; + if (arch === "x86_64" || arch === "x64") + return "x64"; + if (arch === "arm") + return "arm"; + if (arch === "aarch64" || arch === "arm64") + return "arm64"; + if (arch) + return `other:${arch}`; + return "unknown"; +}; +var normalizePlatform = (platform) => { + platform = platform.toLowerCase(); + if (platform.includes("ios")) + return "iOS"; + if (platform === "android") + return "Android"; + if (platform === "darwin") + return "MacOS"; + if (platform === "win32") + return "Windows"; + if (platform === "freebsd") + return "FreeBSD"; + if (platform === "openbsd") + return "OpenBSD"; + if (platform === "linux") + return "Linux"; + if (platform) + return `Other:${platform}`; + return "Unknown"; +}; +var _platformHeaders; +var getPlatformHeaders = () => { + return _platformHeaders ?? (_platformHeaders = getPlatformProperties()); }; -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/parse.mjs -async function defaultParseResponse(client, props) { - const { response, requestLogID, retryOfRequestLogID, startTime } = props; - const body = await (async () => { - if (response.status === 204) { - return null; - } - if (props.options.__binaryResponse) { - return response; - } - const contentType = response.headers.get("content-type"); - const mediaType = contentType?.split(";")[0]?.trim(); - const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json"); - if (isJSON) { - const contentLength = response.headers.get("content-length"); - if (contentLength === "0") { - return void 0; - } - const json = await response.json(); - return json; - } - const text = await response.text(); - return text; - })(); - loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - body, - durationMs: Date.now() - startTime - })); - return body; +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/shims.mjs +function getDefaultFetch() { + if (typeof fetch !== "undefined") { + return fetch; + } + throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Stainless({ fetch })` or polyfill the global, `globalThis.fetch = fetch`"); } - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/core/api-promise.mjs -var _APIPromise_client; -var APIPromise = /* @__PURE__ */ (() => { - class APIPromise4 extends Promise { - constructor(client, responsePromise, parseResponse = defaultParseResponse) { - super((resolve) => { - resolve(null); - }); - this.responsePromise = responsePromise; - this.parseResponse = parseResponse; - _APIPromise_client.set(this, void 0); - __classPrivateFieldSet(this, _APIPromise_client, client, "f"); - } - _thenUnwrap(transform) { - return new APIPromise4(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => transform(await this.parseResponse(client, props), props)); - } - /** - * Gets the raw `Response` instance instead of parsing the response - * data. - * - * If you want to parse the response body but still get the `Response` - * instance, you can use {@link withResponse()}. - * - * 👋 Getting the wrong TypeScript type for `Response`? - * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` - * to your `tsconfig.json`. - */ - asResponse() { - return this.responsePromise.then((p) => p.response); - } - /** - * Gets the parsed response data and the raw `Response` instance. - * - * If you just want to get the raw `Response` instance without parsing it, - * you can use {@link asResponse()}. - * - * 👋 Getting the wrong TypeScript type for `Response`? - * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` - * to your `tsconfig.json`. - */ - async withResponse() { - const [data, response] = await Promise.all([this.parse(), this.asResponse()]); - return { data, response }; - } - parse() { - if (!this.parsedPromise) { - this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data)); +function makeReadableStream(...args) { + const ReadableStream = globalThis.ReadableStream; + if (typeof ReadableStream === "undefined") { + throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`"); + } + return new ReadableStream(...args); +} +function ReadableStreamFrom(iterable) { + let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); + return makeReadableStream({ + start() { + }, + async pull(controller) { + const { done, value } = await iter.next(); + if (done) { + controller.close(); + } else { + controller.enqueue(value); } - return this.parsedPromise; - } - then(onfulfilled, onrejected) { - return this.parse().then(onfulfilled, onrejected); - } - catch(onrejected) { - return this.parse().catch(onrejected); - } - finally(onfinally) { - return this.parse().finally(onfinally); + }, + async cancel() { + await iter.return?.(); } + }); +} +async function CancelReadableStream(stream) { + if (stream === null || typeof stream !== "object") + return; + if (stream[Symbol.asyncIterator]) { + await stream[Symbol.asyncIterator]().return?.(); + return; } - _APIPromise_client = /* @__PURE__ */ new WeakMap(); - return APIPromise4; -})(); + const reader = stream.getReader(); + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; +} -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/core/pagination.mjs -var _AbstractPage_client; -var AbstractPage = /* @__PURE__ */ (() => { - class AbstractPage3 { - constructor(client, response, body, options) { - _AbstractPage_client.set(this, void 0); - __classPrivateFieldSet(this, _AbstractPage_client, client, "f"); - this.options = options; - this.response = response; - this.body = body; - } - hasNextPage() { - const items = this.getPaginatedItems(); - if (!items.length) - return false; - return this.nextPageRequestOptions() != null; - } - async getNextPage() { - const nextOptions = this.nextPageRequestOptions(); - if (!nextOptions) { - throw new GitHubError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`."); +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/request-options.mjs +var FallbackEncoder = ({ headers, body }) => { + return { + bodyHeaders: { + "content-type": "application/json" + }, + body: JSON.stringify(body) + }; +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/qs/formats.mjs +var default_format = "RFC3986"; +var default_formatter = (v) => String(v); +var formatters = { + RFC1738: (v) => String(v).replace(/%20/g, "+"), + RFC3986: default_formatter +}; +var RFC1738 = "RFC1738"; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/qs/utils.mjs +var has = (obj, key) => (has = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has(obj, key)); +var hex_table = /* @__PURE__ */ (() => { + const array = []; + for (let i = 0; i < 256; ++i) { + array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase()); + } + return array; +})(); +var limit = 1024; +var encode = (str, _defaultEncoder, charset, _kind, format) => { + if (str.length === 0) { + return str; + } + let string = str; + if (typeof str === "symbol") { + string = Symbol.prototype.toString.call(str); + } else if (typeof str !== "string") { + string = String(str); + } + if (charset === "iso-8859-1") { + return escape(string).replace(/%u[0-9a-f]{4}/gi, function($0) { + return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; + }); + } + let out = ""; + for (let j = 0; j < string.length; j += limit) { + const segment = string.length >= limit ? string.slice(j, j + limit) : string; + const arr = []; + for (let i = 0; i < segment.length; ++i) { + let c = segment.charCodeAt(i); + if (c === 45 || // - + c === 46 || // . + c === 95 || // _ + c === 126 || // ~ + c >= 48 && c <= 57 || // 0-9 + c >= 65 && c <= 90 || // a-z + c >= 97 && c <= 122 || // A-Z + format === RFC1738 && (c === 40 || c === 41)) { + arr[arr.length] = segment.charAt(i); + continue; } - return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); - } - async *iterPages() { - let page = this; - yield page; - while (page.hasNextPage()) { - page = await page.getNextPage(); - yield page; + if (c < 128) { + arr[arr.length] = hex_table[c]; + continue; } - } - async *[(_AbstractPage_client = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() { - for await (const page of this.iterPages()) { - for (const item of page.getPaginatedItems()) { - yield item; - } + if (c < 2048) { + arr[arr.length] = hex_table[192 | c >> 6] + hex_table[128 | c & 63]; + continue; } - } - } - return AbstractPage3; -})(); -var PagePromise = /* @__PURE__ */ (() => { - class PagePromise3 extends APIPromise { - constructor(client, request, Page2) { - super(client, request, async (client2, props) => new Page2(client2, props.response, await defaultParseResponse(client2, props), props.options)); - } - /** - * Allow auto-paginating iteration on an unawaited list call, eg: - * - * for await (const item of client.items.list()) { - * console.log(item) - * } - */ - async *[Symbol.asyncIterator]() { - const page = await this; - for await (const item of page) { - yield item; + if (c < 55296 || c >= 57344) { + arr[arr.length] = hex_table[224 | c >> 12] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63]; + continue; } + i += 1; + c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023); + arr[arr.length] = hex_table[240 | c >> 18] + hex_table[128 | c >> 12 & 63] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63]; } + out += arr.join(""); } - return PagePromise3; -})(); -var NumberedPage = class extends AbstractPage { - constructor(client, response, body, options) { - super(client, response, body, options); - this.data = body || []; + return out; +}; +function is_buffer(obj) { + if (!obj || typeof obj !== "object") { + return false; } - getPaginatedItems() { - return this.data ?? []; + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +} +function maybe_map(val, fn) { + if (isArray(val)) { + const mapped = []; + for (let i = 0; i < val.length; i += 1) { + mapped.push(fn(val[i])); + } + return mapped; } - nextPageRequestOptions() { - const query = this.options.query; - const currentPage = query?.page ?? 1; - return { - ...this.options, - query: { - ...maybeObj(this.options.query), - page: currentPage + 1 - } - }; + return fn(val); +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/qs/stringify.mjs +var array_prefix_generators = { + brackets(prefix) { + return String(prefix) + "[]"; + }, + comma: "comma", + indices(prefix, key) { + return String(prefix) + "[" + key + "]"; + }, + repeat(prefix) { + return String(prefix); } }; - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/utils/path.mjs -function encodeURIPath(str) { - return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); +var push_to_array = function(arr, value_or_array) { + Array.prototype.push.apply(arr, isArray(value_or_array) ? value_or_array : [value_or_array]); +}; +var toISOString; +var defaults = { + addQueryPrefix: false, + allowDots: false, + allowEmptyArrays: false, + arrayFormat: "indices", + charset: "utf-8", + charsetSentinel: false, + delimiter: "&", + encode: true, + encodeDotInKeys: false, + encoder: encode, + encodeValuesOnly: false, + format: default_format, + formatter: default_formatter, + /** @deprecated */ + indices: false, + serializeDate(date) { + return (toISOString ?? (toISOString = Function.prototype.call.bind(Date.prototype.toISOString)))(date); + }, + skipNulls: false, + strictNullHandling: false +}; +function is_non_nullish_primitive(v) { + return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint"; } -var EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); -var createPathTagFunction = (pathEncoder = encodeURIPath) => function path7(statics, ...params) { - if (statics.length === 1) - return statics[0]; - let postPath = false; - const invalidSegments = []; - const path8 = statics.reduce((previousValue, currentValue, index) => { - if (/[?#]/.test(currentValue)) { - postPath = true; +var sentinel = {}; +function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { + let obj = object; + let tmp_sc = sideChannel; + let step = 0; + let find_flag = false; + while ((tmp_sc = tmp_sc.get(sentinel)) !== void 0 && !find_flag) { + const pos = tmp_sc.get(object); + step += 1; + if (typeof pos !== "undefined") { + if (pos === step) { + throw new RangeError("Cyclic object value"); + } else { + find_flag = true; + } } - const value = params[index]; - let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value); - if (index !== params.length && (value == null || typeof value === "object" && // handle values from other realms - value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY)?.toString)) { - encoded = value + ""; - invalidSegments.push({ - start: previousValue.length + currentValue.length, - length: encoded.length, - error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter` - }); + if (typeof tmp_sc.get(sentinel) === "undefined") { + step = 0; } - return previousValue + currentValue + (index === params.length ? "" : encoded); - }, ""); - const pathOnly = path8.split(/[?#]/, 1)[0]; - const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; - let match; - while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) { - invalidSegments.push({ - start: match.index, - length: match[0].length, - error: `Value "${match[0]}" can't be safely passed as a path parameter` - }); } - invalidSegments.sort((a, b) => a.start - b.start); - if (invalidSegments.length > 0) { - let lastEnd = 0; - const underline = invalidSegments.reduce((acc, segment) => { - const spaces = " ".repeat(segment.start - lastEnd); - const arrows = "^".repeat(segment.length); - lastEnd = segment.start + segment.length; - return acc + spaces + arrows; - }, ""); - throw new GitHubError(`Path parameters result in path with invalid segments: -${invalidSegments.map((e) => e.error).join("\n")} -${path8} -${underline}`); + if (typeof filter === "function") { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate?.(obj); + } else if (generateArrayPrefix === "comma" && isArray(obj)) { + obj = maybe_map(obj, function(value) { + if (value instanceof Date) { + return serializeDate?.(value); + } + return value; + }); } - return path8; -}; -var path = /* @__PURE__ */ createPathTagFunction(encodeURIPath); - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/resources/repos/commits/commits.mjs -var BaseCommits = /* @__PURE__ */ (() => { - class BaseCommits4 extends APIResource { - /** - * Returns the contents of a single commit reference. You must have `read` access - * for the repository to use this endpoint. - * - * > [!NOTE] If there are more than 300 files in the commit diff and the default - * > JSON media type is requested, the response will include pagination link - * > headers for the remaining files, up to a limit of 3000 files. Each page - * > contains the static commit information, and the only changes are to the file - * > listing. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * Pagination query parameters are not supported for these media types. - * - * - **`application/vnd.github.diff`**: Returns the diff of the commit. Larger - * diffs may time out and return a 5xx status code. - * - **`application/vnd.github.patch`**: Returns the patch of the commit. Diffs - * with binary data will have no `patch` property. Larger diffs may time out and - * return a 5xx status code. - * - **`application/vnd.github.sha`**: Returns the commit's SHA-1 hash. You can use - * this endpoint to check if a remote reference's SHA-1 hash is the same as your - * local reference's SHA-1 hash by providing the local SHA-1 reference as the - * ETag. - * - * **Signature verification object** - * - * The response will include a `verification` object that describes the result of - * verifying the commit's signature. The following fields are included in the - * `verification` object: - * - * | Name | Type | Description | - * | ------------- | --------- | ------------------------------------------------------------------------------------------------ | - * | `verified` | `boolean` | Indicates whether GitHub considers the signature in this commit to be verified. | - * | `reason` | `string` | The reason for verified value. Possible values and their meanings are enumerated in table below. | - * | `signature` | `string` | The signature that was extracted from the commit. | - * | `payload` | `string` | The value that was signed. | - * | `verified_at` | `string` | The date the signature was verified by GitHub. | - * - * These are the possible values for `reason` in the `verification` object: - * - * | Value | Description | - * | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------- | - * | `expired_key` | The key that made the signature is expired. | - * | `not_signing_key` | The "signing" flag is not among the usage flags in the GPG key that made the signature. | - * | `gpgverify_error` | There was an error communicating with the signature verification service. | - * | `gpgverify_unavailable` | The signature verification service is currently unavailable. | - * | `unsigned` | The object does not include a signature. | - * | `unknown_signature_type` | A non-PGP signature was found in the commit. | - * | `no_user` | No user was associated with the `committer` email address in the commit. | - * | `unverified_email` | The `committer` email address in the commit was associated with a user, but the email address is not verified on their account. | - * | `bad_email` | The `committer` email address in the commit is not included in the identities of the PGP key that made the signature. | - * | `unknown_key` | The key that made the signature has not been registered with any user's account. | - * | `malformed_signature` | There was an error parsing the signature. | - * | `invalid` | The signature could not be cryptographically verified using the key whose key-id was found in the signature. | - * | `valid` | None of the above errors applied, so the signature is considered to be verified. | - * - * @example - * ```ts - * const commit = await client.repos.commits.retrieve('ref', { - * owner: 'owner', - * repo: 'repo', - * }); - * ``` - */ - retrieve(ref, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/commits/${ref}`, { query, ...options }); - } - /** - * **Signature verification object** - * - * The response will include a `verification` object that describes the result of - * verifying the commit's signature. The following fields are included in the - * `verification` object: - * - * | Name | Type | Description | - * | ------------- | --------- | ------------------------------------------------------------------------------------------------ | - * | `verified` | `boolean` | Indicates whether GitHub considers the signature in this commit to be verified. | - * | `reason` | `string` | The reason for verified value. Possible values and their meanings are enumerated in table below. | - * | `signature` | `string` | The signature that was extracted from the commit. | - * | `payload` | `string` | The value that was signed. | - * | `verified_at` | `string` | The date the signature was verified by GitHub. | - * - * These are the possible values for `reason` in the `verification` object: - * - * | Value | Description | - * | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------- | - * | `expired_key` | The key that made the signature is expired. | - * | `not_signing_key` | The "signing" flag is not among the usage flags in the GPG key that made the signature. | - * | `gpgverify_error` | There was an error communicating with the signature verification service. | - * | `gpgverify_unavailable` | The signature verification service is currently unavailable. | - * | `unsigned` | The object does not include a signature. | - * | `unknown_signature_type` | A non-PGP signature was found in the commit. | - * | `no_user` | No user was associated with the `committer` email address in the commit. | - * | `unverified_email` | The `committer` email address in the commit was associated with a user, but the email address is not verified on their account. | - * | `bad_email` | The `committer` email address in the commit is not included in the identities of the PGP key that made the signature. | - * | `unknown_key` | The key that made the signature has not been registered with any user's account. | - * | `malformed_signature` | There was an error parsing the signature. | - * | `invalid` | The signature could not be cryptographically verified using the key whose key-id was found in the signature. | - * | `valid` | None of the above errors applied, so the signature is considered to be verified. | - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const commit of client.repos.commits.list({ - * owner: 'owner', - * repo: 'repo', - * })) { - * // ... - * } - * ``` - */ - list(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.getAPIList(path`/repos/${owner}/${repo}/commits`, NumberedPage, { - query, - ...options - }); + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? ( + // @ts-expect-error + encoder(prefix, defaults.encoder, charset, "key", format) + ) : prefix; } - /** - * Protected branches are available in public repositories with GitHub Free and - * GitHub Free for organizations, and in public and private repositories with - * GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. - * For more information, see - * [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) - * in the GitHub Help documentation. - * - * Returns all branches where the given commit SHA is the HEAD, or latest commit - * for the branch. - * - * @example - * ```ts - * const response = - * await client.repos.commits.listBranchesWhereHead( - * 'commit_sha', - * { owner: 'owner', repo: 'repo' }, - * ); - * ``` - */ - listBranchesWhereHead(commitSha, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/commits/${commitSha}/branches-where-head`, options); + obj = ""; + } + if (is_non_nullish_primitive(obj) || is_buffer(obj)) { + if (encoder) { + const key_value = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, "key", format); + return [ + formatter?.(key_value) + "=" + // @ts-expect-error + formatter?.(encoder(obj, defaults.encoder, charset, "value", format)) + ]; } - /** - * Lists check runs for a commit ref. The `ref` can be a SHA, branch name, or a tag - * name. - * - * > [!NOTE] The endpoints to manage checks only look for pushes in the repository - * > where the check suite or check run were created. Pushes to a branch in a - * > forked repository are not detected and return an empty `pull_requests` array. - * - * If there are more than 1000 check suites on a single git reference, this - * endpoint will limit check runs to the 1000 most recent check suites. To iterate - * over all possible check runs, use the - * [List check suites for a Git reference](https://docs.github.com/rest/reference/checks#list-check-suites-for-a-git-reference) - * endpoint and provide the `check_suite_id` parameter to the - * [List check runs in a check suite](https://docs.github.com/rest/reference/checks#list-check-runs-in-a-check-suite) - * endpoint. - * - * OAuth app tokens and personal access tokens (classic) need the `repo` scope to - * use this endpoint on a private repository. - * - * @example - * ```ts - * const response = await client.repos.commits.listCheckRuns( - * 'ref', - * { owner: 'owner', repo: 'repo' }, - * ); - * ``` - */ - listCheckRuns(ref, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/commits/${ref}/check-runs`, { query, ...options }); + return [formatter?.(prefix) + "=" + formatter?.(String(obj))]; + } + const values = []; + if (typeof obj === "undefined") { + return values; + } + let obj_keys; + if (generateArrayPrefix === "comma" && isArray(obj)) { + if (encodeValuesOnly && encoder) { + obj = maybe_map(obj, encoder); } - /** - * Lists check suites for a commit `ref`. The `ref` can be a SHA, branch name, or a - * tag name. - * - * > [!NOTE] The endpoints to manage checks only look for pushes in the repository - * > where the check suite or check run were created. Pushes to a branch in a - * > forked repository are not detected and return an empty `pull_requests` array - * > and a `null` value for `head_branch`. - * - * OAuth app tokens and personal access tokens (classic) need the `repo` scope to - * use this endpoint on a private repository. - * - * @example - * ```ts - * const response = await client.repos.commits.listCheckSuites( - * 'ref', - * { owner: 'owner', repo: 'repo' }, - * ); - * ``` - */ - listCheckSuites(ref, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/commits/${ref}/check-suites`, { query, ...options }); - } - /** - * Lists the merged pull request that introduced the commit to the repository. If - * the commit is not present in the default branch, it will return merged and open - * pull requests associated with the commit. - * - * To list the open or merged pull requests associated with a branch, you can set - * the `commit_sha` parameter to the branch name. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const pullRequestSimple of client.repos.commits.listPullRequests( - * 'commit_sha', - * { owner: 'owner', repo: 'repo' }, - * )) { - * // ... - * } - * ``` - */ - listPullRequests(commitSha, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.getAPIList(path`/repos/${owner}/${repo}/commits/${commitSha}/pulls`, NumberedPage, { query, ...options }); - } - /** - * Users with pull access in a repository can view commit statuses for a given ref. - * The ref can be a SHA, a branch name, or a tag name. Statuses are returned in - * reverse chronological order. The first status in the list will be the latest - * one. - * - * This resource is also available via a legacy route: - * `GET /repos/:owner/:repo/statuses/:ref`. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const commitListStatusesResponse of client.repos.commits.listStatuses( - * 'ref', - * { owner: 'owner', repo: 'repo' }, - * )) { - * // ... - * } - * ``` - */ - listStatuses(ref, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.getAPIList(path`/repos/${owner}/${repo}/commits/${ref}/statuses`, NumberedPage, { query, ...options }); - } - /** - * Users with pull access in a repository can access a combined view of commit - * statuses for a given ref. The ref can be a SHA, a branch name, or a tag name. - * - * Additionally, a combined `state` is returned. The `state` is one of: - * - * - **failure** if any of the contexts report as `error` or `failure` - * - **pending** if there are no statuses or a context is `pending` - * - **success** if the latest status for all contexts is `success` - * - * @example - * ```ts - * const response = await client.repos.commits.retrieveStatus( - * 'ref', - * { owner: 'owner', repo: 'repo' }, - * ); - * ``` - */ - retrieveStatus(ref, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/commits/${ref}/status`, { query, ...options }); + obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; + } else if (isArray(filter)) { + obj_keys = filter; + } else { + const keys = Object.keys(obj); + obj_keys = sort ? keys.sort(sort) : keys; + } + const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix); + const adjusted_prefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix; + if (allowEmptyArrays && isArray(obj) && obj.length === 0) { + return adjusted_prefix + "[]"; + } + for (let j = 0; j < obj_keys.length; ++j) { + const key = obj_keys[j]; + const value = ( + // @ts-ignore + typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key] + ); + if (skipNulls && value === null) { + continue; } + const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key; + const key_prefix = isArray(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]"); + sideChannel.set(object, step); + const valueSideChannel = /* @__PURE__ */ new WeakMap(); + valueSideChannel.set(sentinel, sideChannel); + push_to_array(values, inner_stringify( + value, + key_prefix, + generateArrayPrefix, + commaRoundTrip, + allowEmptyArrays, + strictNullHandling, + skipNulls, + encodeDotInKeys, + // @ts-ignore + generateArrayPrefix === "comma" && encodeValuesOnly && isArray(obj) ? null : encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + valueSideChannel + )); } - BaseCommits4._key = Object.freeze(["repos", "commits"]); - return BaseCommits4; -})(); - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/headers.mjs -var brand_privateNullableHeaders = /* @__PURE__ */ Symbol("brand.privateNullableHeaders"); -function* iterateHeaders(headers) { - if (!headers) - return; - if (brand_privateNullableHeaders in headers) { - const { values, nulls } = headers; - yield* values.entries(); - for (const name of nulls) { - yield [name, null]; + return values; +} +function normalize_stringify_options(opts = defaults) { + if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") { + throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); + } + if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") { + throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided"); + } + if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") { + throw new TypeError("Encoder has to be a function."); + } + const charset = opts.charset || defaults.charset; + if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { + throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); + } + let format = default_format; + if (typeof opts.format !== "undefined") { + if (!has(formatters, opts.format)) { + throw new TypeError("Unknown format option provided."); } - return; + format = opts.format; } - let shouldClear = false; - let iter; - if (headers instanceof Headers) { - iter = headers.entries(); - } else if (isReadonlyArray(headers)) { - iter = headers; + const formatter = formatters[format]; + let filter = defaults.filter; + if (typeof opts.filter === "function" || isArray(opts.filter)) { + filter = opts.filter; + } + let arrayFormat; + if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) { + arrayFormat = opts.arrayFormat; + } else if ("indices" in opts) { + arrayFormat = opts.indices ? "indices" : "repeat"; } else { - shouldClear = true; - iter = Object.entries(headers ?? {}); + arrayFormat = defaults.arrayFormat; } - for (let row of iter) { - const name = row[0]; - if (typeof name !== "string") - throw new TypeError("expected header name to be a string"); - const values = isReadonlyArray(row[1]) ? row[1] : [row[1]]; - let didClear = false; - for (const value of values) { - if (value === void 0) - continue; - if (shouldClear && !didClear) { - didClear = true; - yield [name, null]; - } - yield [name, value]; - } + if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") { + throw new TypeError("`commaRoundTrip` must be a boolean, or absent"); } + const allowDots = typeof opts.allowDots === "undefined" ? !!opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; + return { + addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix, + // @ts-ignore + allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, + arrayFormat, + charset, + charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel, + commaRoundTrip: !!opts.commaRoundTrip, + delimiter: typeof opts.delimiter === "undefined" ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === "boolean" ? opts.encode : defaults.encode, + encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults.encodeDotInKeys, + encoder: typeof opts.encoder === "function" ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter, + format, + formatter, + serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults.skipNulls, + // @ts-ignore + sort: typeof opts.sort === "function" ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling + }; } -var buildHeaders = (newHeaders) => { - const targetHeaders = new Headers(); - const nullHeaders = /* @__PURE__ */ new Set(); - for (const headers of newHeaders) { - const seenHeaders = /* @__PURE__ */ new Set(); - for (const [name, value] of iterateHeaders(headers)) { - const lowerName = name.toLowerCase(); - if (!seenHeaders.has(lowerName)) { - targetHeaders.delete(name); - seenHeaders.add(lowerName); - } - if (value === null) { - targetHeaders.delete(name); - nullHeaders.add(lowerName); - } else { - targetHeaders.append(name, value); - nullHeaders.delete(lowerName); - } +function stringify(object, opts = {}) { + let obj = object; + const options = normalize_stringify_options(opts); + let obj_keys; + let filter; + if (typeof options.filter === "function") { + filter = options.filter; + obj = filter("", obj); + } else if (isArray(options.filter)) { + filter = options.filter; + obj_keys = filter; + } + const keys = []; + if (typeof obj !== "object" || obj === null) { + return ""; + } + const generateArrayPrefix = array_prefix_generators[options.arrayFormat]; + const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip; + if (!obj_keys) { + obj_keys = Object.keys(obj); + } + if (options.sort) { + obj_keys.sort(options.sort); + } + const sideChannel = /* @__PURE__ */ new WeakMap(); + for (let i = 0; i < obj_keys.length; ++i) { + const key = obj_keys[i]; + if (options.skipNulls && obj[key] === null) { + continue; + } + push_to_array(keys, inner_stringify( + obj[key], + key, + // @ts-expect-error + generateArrayPrefix, + commaRoundTrip, + options.allowEmptyArrays, + options.strictNullHandling, + options.skipNulls, + options.encodeDotInKeys, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.format, + options.formatter, + options.encodeValuesOnly, + options.charset, + sideChannel + )); + } + const joined = keys.join(options.delimiter); + let prefix = options.addQueryPrefix === true ? "?" : ""; + if (options.charsetSentinel) { + if (options.charset === "iso-8859-1") { + prefix += "utf8=%26%2310003%3B&"; + } else { + prefix += "utf8=%E2%9C%93&"; } } - return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders }; -}; + return joined.length > 0 ? prefix + joined : ""; +} -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/resources/repos/issues/comments/comments.mjs -var BaseComments2 = /* @__PURE__ */ (() => { - class BaseComments8 extends APIResource { - /** - * You can use the REST API to create comments on issues and pull requests. Every - * pull request is an issue, but not every issue is a pull request. - * - * This endpoint triggers - * [notifications](https://docs.github.com/github/managing-subscriptions-and-notifications-on-github/about-notifications). - * Creating content too quickly using this endpoint may result in secondary rate - * limiting. For more information, see - * "[Rate limits for the API](https://docs.github.com/rest/using-the-rest-api/rate-limits-for-the-rest-api#about-secondary-rate-limits)" - * and - * "[Best practices for using the REST API](https://docs.github.com/rest/guides/best-practices-for-using-the-rest-api)." - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response - * will include `body`. This is the default if you do not pass any specific media - * type. - * - **`application/vnd.github.text+json`**: Returns a text only representation of - * the markdown body. Response will include `body_text`. - * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's - * markdown. Response will include `body_html`. - * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML - * representations. Response will include `body`, `body_text`, and `body_html`. - * - * @example - * ```ts - * const issueComment = - * await client.repos.issues.comments.create(0, { - * owner: 'owner', - * repo: 'repo', - * body: 'Me too', - * }); - * ``` - */ - create(issueNumber, params, options) { - const { owner = this._client.owner, repo = this._client.repo, ...body } = params; - return this._client.post(path`/repos/${owner}/${repo}/issues/${issueNumber}/comments`, { - body, - ...options - }); +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/query.mjs +function stringifyQuery(query) { + return stringify(query, { arrayFormat: "comma" }); +} + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/log.mjs +var levelNumbers = { + off: 0, + error: 200, + warn: 300, + info: 400, + debug: 500 +}; +var parseLogLevel = (maybeLevel, sourceName, client) => { + if (!maybeLevel) { + return void 0; + } + if (hasOwn(levelNumbers, maybeLevel)) { + return maybeLevel; + } + loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`); + return void 0; +}; +function noop() { +} +function makeLogFn(fnLevel, logger2, logLevel) { + if (!logger2 || levelNumbers[fnLevel] > levelNumbers[logLevel]) { + return noop; + } else { + return logger2[fnLevel].bind(logger2); + } +} +var noopLogger = { + error: noop, + warn: noop, + info: noop, + debug: noop +}; +var cachedLoggers = /* @__PURE__ */ new WeakMap(); +function loggerFor(client) { + const logger2 = client.logger; + const logLevel = client.logLevel ?? "off"; + if (!logger2) { + return noopLogger; + } + const cachedLogger = cachedLoggers.get(logger2); + if (cachedLogger && cachedLogger[0] === logLevel) { + return cachedLogger[1]; + } + const levelLogger = { + error: makeLogFn("error", logger2, logLevel), + warn: makeLogFn("warn", logger2, logLevel), + info: makeLogFn("info", logger2, logLevel), + debug: makeLogFn("debug", logger2, logLevel) + }; + cachedLoggers.set(logger2, [logLevel, levelLogger]); + return levelLogger; +} +var formatRequestDetails = (details) => { + if (details.options) { + details.options = { ...details.options }; + delete details.options["headers"]; + } + if (details.headers) { + details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ + name, + name.toLowerCase() === "authorization" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value + ])); + } + if ("retryOfRequestLogID" in details) { + if (details.retryOfRequestLogID) { + details.retryOf = details.retryOfRequestLogID; } - /** - * You can use the REST API to get comments on issues and pull requests. Every pull - * request is an issue, but not every issue is a pull request. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response - * will include `body`. This is the default if you do not pass any specific media - * type. - * - **`application/vnd.github.text+json`**: Returns a text only representation of - * the markdown body. Response will include `body_text`. - * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's - * markdown. Response will include `body_html`. - * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML - * representations. Response will include `body`, `body_text`, and `body_html`. - * - * @example - * ```ts - * const issueComment = - * await client.repos.issues.comments.retrieve(0, { - * owner: 'owner', - * repo: 'repo', - * }); - * ``` - */ - retrieve(commentID, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/issues/comments/${commentID}`, options); + delete details.retryOfRequestLogID; + } + return details; +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/parse.mjs +async function defaultParseResponse(client, props) { + const { response, requestLogID, retryOfRequestLogID, startTime } = props; + const body = await (async () => { + if (response.status === 204) { + return null; } - /** - * You can use the REST API to update comments on issues and pull requests. Every - * pull request is an issue, but not every issue is a pull request. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response - * will include `body`. This is the default if you do not pass any specific media - * type. - * - **`application/vnd.github.text+json`**: Returns a text only representation of - * the markdown body. Response will include `body_text`. - * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's - * markdown. Response will include `body_html`. - * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML - * representations. Response will include `body`, `body_text`, and `body_html`. - * - * @example - * ```ts - * const issueComment = - * await client.repos.issues.comments.update(0, { - * owner: 'owner', - * repo: 'repo', - * body: 'Me too', - * }); - * ``` - */ - update(commentID, params, options) { - const { owner = this._client.owner, repo = this._client.repo, ...body } = params; - return this._client.patch(path`/repos/${owner}/${repo}/issues/comments/${commentID}`, { - body, - ...options - }); + if (props.options.__binaryResponse) { + return response; } - async upsertBasedOnBodyMatch(issueNumber, { bodyIncludes, createParams, updateParams, options }) { - const comments = await this.list(issueNumber); - const match = comments.data.find((comment) => comment.body?.includes(bodyIncludes)); - if (match) { - return this.update(match.id, updateParams, options); - } else { - return this.create(issueNumber, createParams, options); + const contentType = response.headers.get("content-type"); + const mediaType = contentType?.split(";")[0]?.trim(); + const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json"); + if (isJSON) { + const contentLength = response.headers.get("content-length"); + if (contentLength === "0") { + return void 0; } + const json = await response.json(); + return json; } - /** - * You can use the REST API to list comments on issues and pull requests. Every - * pull request is an issue, but not every issue is a pull request. - * - * Issue comments are ordered by ascending ID. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response - * will include `body`. This is the default if you do not pass any specific media - * type. - * - **`application/vnd.github.text+json`**: Returns a text only representation of - * the markdown body. Response will include `body_text`. - * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's - * markdown. Response will include `body_html`. - * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML - * representations. Response will include `body`, `body_text`, and `body_html`. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const issueComment of client.repos.issues.comments.list( - * 0, - * { owner: 'owner', repo: 'repo' }, - * )) { - * // ... - * } - * ``` - */ - list(issueNumber, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.getAPIList(path`/repos/${owner}/${repo}/issues/${issueNumber}/comments`, NumberedPage, { query, ...options }); - } - /** - * You can use the REST API to delete comments on issues and pull requests. Every - * pull request is an issue, but not every issue is a pull request. - * - * @example - * ```ts - * await client.repos.issues.comments.delete(0, { - * owner: 'owner', - * repo: 'repo', - * }); - * ``` - */ - delete(commentID, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; - return this._client.delete(path`/repos/${owner}/${repo}/issues/comments/${commentID}`, { - ...options, - headers: buildHeaders([{ Accept: "*/*" }, options?.headers]) - }); - } - } - BaseComments8._key = Object.freeze([ - "repos", - "issues", - "comments" - ]); - return BaseComments8; -})(); + const text = await response.text(); + return text; + })(); + loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + body, + durationMs: Date.now() - startTime + })); + return body; +} -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/resources/repos/pulls/pulls.mjs -var BasePulls = /* @__PURE__ */ (() => { - class BasePulls2 extends APIResource { - /** - * Draft pull requests are available in public repositories with GitHub Free and - * GitHub Free for organizations, GitHub Pro, and legacy per-repository billing - * plans, and in public and private repositories with GitHub Team and GitHub - * Enterprise Cloud. For more information, see - * [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) - * in the GitHub Help documentation. - * - * To open or update a pull request in a public repository, you must have write - * access to the head or the source branch. For organization-owned repositories, - * you must be a member of the organization that owns the repository to open or - * update a pull request. - * - * This endpoint triggers - * [notifications](https://docs.github.com/github/managing-subscriptions-and-notifications-on-github/about-notifications). - * Creating content too quickly using this endpoint may result in secondary rate - * limiting. For more information, see - * "[Rate limits for the API](https://docs.github.com/rest/using-the-rest-api/rate-limits-for-the-rest-api#about-secondary-rate-limits)" - * and - * "[Best practices for using the REST API](https://docs.github.com/rest/guides/best-practices-for-using-the-rest-api)." - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response - * will include `body`. This is the default if you do not pass any specific media - * type. - * - **`application/vnd.github.text+json`**: Returns a text only representation of - * the markdown body. Response will include `body_text`. - * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's - * markdown. Response will include `body_html`. - * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML - * representations. Response will include `body`, `body_text`, and `body_html`. - * - * @example - * ```ts - * const pullRequest = await client.repos.pulls.create({ - * owner: 'owner', - * repo: 'repo', - * base: 'master', - * head: 'octocat:new-feature', - * body: 'Please pull these awesome changes in!', - * title: 'Amazing new feature', - * }); - * ``` - */ - create(params, options) { - const { owner = this._client.owner, repo = this._client.repo, ...body } = params; - return this._client.post(path`/repos/${owner}/${repo}/pulls`, { body, ...options }); - } - /** - * Draft pull requests are available in public repositories with GitHub Free and - * GitHub Free for organizations, GitHub Pro, and legacy per-repository billing - * plans, and in public and private repositories with GitHub Team and GitHub - * Enterprise Cloud. For more information, see - * [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) - * in the GitHub Help documentation. - * - * Lists details of a pull request by providing its number. - * - * When you get, - * [create](https://docs.github.com/rest/pulls/pulls/#create-a-pull-request), or - * [edit](https://docs.github.com/rest/pulls/pulls#update-a-pull-request) a pull - * request, GitHub creates a merge commit to test whether the pull request can be - * automatically merged into the base branch. This test commit is not added to the - * base branch or the head branch. You can review the status of the test commit - * using the `mergeable` key. For more information, see - * "[Checking mergeability of pull requests](https://docs.github.com/rest/guides/getting-started-with-the-git-database-api#checking-mergeability-of-pull-requests)". - * - * The value of the `mergeable` attribute can be `true`, `false`, or `null`. If the - * value is `null`, then GitHub has started a background job to compute the - * mergeability. After giving the job time to complete, resubmit the request. When - * the job finishes, you will see a non-`null` value for the `mergeable` attribute - * in the response. If `mergeable` is `true`, then `merge_commit_sha` will be the - * SHA of the _test_ merge commit. - * - * The value of the `merge_commit_sha` attribute changes depending on the state of - * the pull request. Before merging a pull request, the `merge_commit_sha` - * attribute holds the SHA of the _test_ merge commit. After merging a pull - * request, the `merge_commit_sha` attribute changes depending on how you merged - * the pull request: - * - * - If merged as a - * [merge commit](https://docs.github.com/articles/about-merge-methods-on-github/), - * `merge_commit_sha` represents the SHA of the merge commit. - * - If merged via a - * [squash](https://docs.github.com/articles/about-merge-methods-on-github/#squashing-your-merge-commits), - * `merge_commit_sha` represents the SHA of the squashed commit on the base - * branch. - * - If - * [rebased](https://docs.github.com/articles/about-merge-methods-on-github/#rebasing-and-merging-your-commits), - * `merge_commit_sha` represents the commit that the base branch was updated to. - * - * Pass the appropriate - * [media type](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types) - * to fetch diff and patch formats. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response - * will include `body`. This is the default if you do not pass any specific media - * type. - * - **`application/vnd.github.text+json`**: Returns a text only representation of - * the markdown body. Response will include `body_text`. - * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's - * markdown. Response will include `body_html`. - * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML - * representations. Response will include `body`, `body_text`, and `body_html`. - * - **`application/vnd.github.diff`**: For more information, see - * "[git-diff](https://git-scm.com/docs/git-diff)" in the Git documentation. If a - * diff is corrupt, contact us through the - * [GitHub Support portal](https://support.github.com/). Include the repository - * name and pull request ID in your message. - * - * @example - * ```ts - * const pullRequest = await client.repos.pulls.retrieve(0, { - * owner: 'owner', - * repo: 'repo', - * }); - * ``` - */ - retrieve(pullNumber, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/pulls/${pullNumber}`, options); +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/core/api-promise.mjs +var _APIPromise_client; +var APIPromise = class _APIPromise extends Promise { + constructor(client, responsePromise, parseResponse = defaultParseResponse) { + super((resolve) => { + resolve(null); + }); + this.responsePromise = responsePromise; + this.parseResponse = parseResponse; + _APIPromise_client.set(this, void 0); + __classPrivateFieldSet(this, _APIPromise_client, client, "f"); + } + _thenUnwrap(transform) { + return new _APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => transform(await this.parseResponse(client, props), props)); + } + /** + * Gets the raw `Response` instance instead of parsing the response + * data. + * + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + asResponse() { + return this.responsePromise.then((p) => p.response); + } + /** + * Gets the parsed response data and the raw `Response` instance. + * + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + async withResponse() { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { data, response }; + } + parse() { + if (!this.parsedPromise) { + this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data)); } - /** - * Draft pull requests are available in public repositories with GitHub Free and - * GitHub Free for organizations, GitHub Pro, and legacy per-repository billing - * plans, and in public and private repositories with GitHub Team and GitHub - * Enterprise Cloud. For more information, see - * [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) - * in the GitHub Help documentation. - * - * To open or update a pull request in a public repository, you must have write - * access to the head or the source branch. For organization-owned repositories, - * you must be a member of the organization that owns the repository to open or - * update a pull request. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response - * will include `body`. This is the default if you do not pass any specific media - * type. - * - **`application/vnd.github.text+json`**: Returns a text only representation of - * the markdown body. Response will include `body_text`. - * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's - * markdown. Response will include `body_html`. - * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML - * representations. Response will include `body`, `body_text`, and `body_html`. - * - * @example - * ```ts - * const pullRequest = await client.repos.pulls.update(0, { - * owner: 'owner', - * repo: 'repo', - * base: 'master', - * body: 'updated body', - * state: 'open', - * title: 'new title', - * }); - * ``` - */ - update(pullNumber, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...body } = params ?? {}; - return this._client.patch(path`/repos/${owner}/${repo}/pulls/${pullNumber}`, { body, ...options }); + return this.parsedPromise; + } + then(onfulfilled, onrejected) { + return this.parse().then(onfulfilled, onrejected); + } + catch(onrejected) { + return this.parse().catch(onrejected); + } + finally(onfinally) { + return this.parse().finally(onfinally); + } +}; +_APIPromise_client = /* @__PURE__ */ new WeakMap(); + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/core/pagination.mjs +var _AbstractPage_client; +var AbstractPage = class { + constructor(client, response, body, options) { + _AbstractPage_client.set(this, void 0); + __classPrivateFieldSet(this, _AbstractPage_client, client, "f"); + this.options = options; + this.response = response; + this.body = body; + } + hasNextPage() { + const items = this.getPaginatedItems(); + if (!items.length) + return false; + return this.nextPageRequestOptions() != null; + } + async getNextPage() { + const nextOptions = this.nextPageRequestOptions(); + if (!nextOptions) { + throw new StainlessError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`."); } - /** - * Lists pull requests in a specified repository. - * - * Draft pull requests are available in public repositories with GitHub Free and - * GitHub Free for organizations, GitHub Pro, and legacy per-repository billing - * plans, and in public and private repositories with GitHub Team and GitHub - * Enterprise Cloud. For more information, see - * [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) - * in the GitHub Help documentation. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response - * will include `body`. This is the default if you do not pass any specific media - * type. - * - **`application/vnd.github.text+json`**: Returns a text only representation of - * the markdown body. Response will include `body_text`. - * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's - * markdown. Response will include `body_html`. - * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML - * representations. Response will include `body`, `body_text`, and `body_html`. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const pullRequestSimple of client.repos.pulls.list( - * { owner: 'owner', repo: 'repo' }, - * )) { - * // ... - * } - * ``` - */ - list(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.getAPIList(path`/repos/${owner}/${repo}/pulls`, NumberedPage, { - query, - ...options - }); + return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); + } + async *iterPages() { + let page = this; + yield page; + while (page.hasNextPage()) { + page = await page.getNextPage(); + yield page; } - /** - * Creates a codespace owned by the authenticated user for the specified pull - * request. - * - * OAuth app tokens and personal access tokens (classic) need the `codespace` scope - * to use this endpoint. - * - * @example - * ```ts - * const codespace = await client.repos.pulls.createCodespace( - * 0, - * { owner: 'owner', repo: 'repo' }, - * ); - * ``` - */ - createCodespace(pullNumber, params, options) { - const { owner = this._client.owner, repo = this._client.repo, ...body } = params; - return this._client.post(path`/repos/${owner}/${repo}/pulls/${pullNumber}/codespaces`, { - body, - ...options - }); + } + async *[(_AbstractPage_client = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() { + for await (const page of this.iterPages()) { + for (const item of page.getPaginatedItems()) { + yield item; + } } - /** - * Creates a review comment on the diff of a specified pull request. To add a - * regular comment to a pull request timeline, see - * "[Create an issue comment](https://docs.github.com/rest/issues/comments#create-an-issue-comment)." - * - * If your comment applies to more than one line in the pull request diff, you - * should use the parameters `line`, `side`, and optionally `start_line` and - * `start_side` in your request. - * - * The `position` parameter is closing down. If you use `position`, the `line`, - * `side`, `start_line`, and `start_side` parameters are not required. - * - * This endpoint triggers - * [notifications](https://docs.github.com/github/managing-subscriptions-and-notifications-on-github/about-notifications). - * Creating content too quickly using this endpoint may result in secondary rate - * limiting. For more information, see - * "[Rate limits for the API](https://docs.github.com/rest/using-the-rest-api/rate-limits-for-the-rest-api#about-secondary-rate-limits)" - * and - * "[Best practices for using the REST API](https://docs.github.com/rest/guides/best-practices-for-using-the-rest-api)." - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github-commitcomment.raw+json`**: Returns the raw markdown - * body. Response will include `body`. This is the default if you do not pass any - * specific media type. - * - **`application/vnd.github-commitcomment.text+json`**: Returns a text only - * representation of the markdown body. Response will include `body_text`. - * - **`application/vnd.github-commitcomment.html+json`**: Returns HTML rendered - * from the body's markdown. Response will include `body_html`. - * - **`application/vnd.github-commitcomment.full+json`**: Returns raw, text, and - * HTML representations. Response will include `body`, `body_text`, and - * `body_html`. - * - * @example - * ```ts - * const response = await client.repos.pulls.createComment(0, { - * owner: 'owner', - * repo: 'repo', - * body: 'Great stuff!', - * commit_id: '6dcb09b5b57875f334f61aebed695e2e4193db5e', - * path: 'file1.txt', - * line: 2, - * side: 'RIGHT', - * start_line: 1, - * start_side: 'RIGHT', - * }); - * ``` - */ - createComment(pullNumber, params, options) { - const { owner = this._client.owner, repo = this._client.repo, ...body } = params; - return this._client.post(path`/repos/${owner}/${repo}/pulls/${pullNumber}/comments`, { - body, - ...options - }); + } +}; +var PagePromise = class extends APIPromise { + constructor(client, request, Page2) { + super(client, request, async (client2, props) => new Page2(client2, props.response, await defaultParseResponse(client2, props), props.options)); + } + /** + * Allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ + async *[Symbol.asyncIterator]() { + const page = await this; + for await (const item of page) { + yield item; } - /** - * Lists all review comments for a specified pull request. By default, review - * comments are in ascending order by ID. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github-commitcomment.raw+json`**: Returns the raw markdown - * body. Response will include `body`. This is the default if you do not pass any - * specific media type. - * - **`application/vnd.github-commitcomment.text+json`**: Returns a text only - * representation of the markdown body. Response will include `body_text`. - * - **`application/vnd.github-commitcomment.html+json`**: Returns HTML rendered - * from the body's markdown. Response will include `body_html`. - * - **`application/vnd.github-commitcomment.full+json`**: Returns raw, text, and - * HTML representations. Response will include `body`, `body_text`, and - * `body_html`. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const pullListCommentsResponse of client.repos.pulls.listComments( - * 0, - * { owner: 'owner', repo: 'repo' }, - * )) { - * // ... - * } - * ``` - */ - listComments(pullNumber, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.getAPIList(path`/repos/${owner}/${repo}/pulls/${pullNumber}/comments`, NumberedPage, { query, ...options }); + } +}; +var Page = class extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.next_cursor = body.next_cursor || ""; + } + getPaginatedItems() { + return this.data ?? []; + } + nextPageRequestOptions() { + const cursor = this.next_cursor; + if (!cursor) { + return null; } - /** - * Lists a maximum of 250 commits for a pull request. To receive a complete commit - * list for pull requests with more than 250 commits, use the - * [List commits](https://docs.github.com/rest/commits/commits#list-commits) - * endpoint. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response - * will include `body`. This is the default if you do not pass any specific media - * type. - * - **`application/vnd.github.text+json`**: Returns a text only representation of - * the markdown body. Response will include `body_text`. - * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's - * markdown. Response will include `body_html`. - * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML - * representations. Response will include `body`, `body_text`, and `body_html`. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const commit of client.repos.pulls.listCommits( - * 0, - * { owner: 'owner', repo: 'repo' }, - * )) { - * // ... - * } - * ``` - */ - listCommits(pullNumber, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.getAPIList(path`/repos/${owner}/${repo}/pulls/${pullNumber}/commits`, NumberedPage, { query, ...options }); + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + cursor + } + }; + } +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/uploads.mjs +var checkFileSupport = () => { + if (typeof File === "undefined") { + const { process: process7 } = globalThis; + const isOldNode = typeof process7?.versions?.node === "string" && parseInt(process7.versions.node.split(".")) < 20; + throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : "")); + } +}; +function makeFile(fileBits, fileName, options) { + checkFileSupport(); + return new File(fileBits, fileName ?? "unknown_file", options); +} +function getName(value) { + return (typeof value === "object" && value !== null && ("name" in value && value.name && String(value.name) || "url" in value && value.url && String(value.url) || "filename" in value && value.filename && String(value.filename) || "path" in value && value.path && String(value.path)) || "").split(/[\\/]/).pop() || void 0; +} +var isAsyncIterable = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function"; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/to-file.mjs +var isBlobLike = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function"; +var isFileLike = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value); +var isResponseLike = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function"; +async function toFile(value, name, options) { + checkFileSupport(); + value = await value; + if (isFileLike(value)) { + if (value instanceof File) { + return value; } - /** - * Lists the files in a specified pull request. - * - * > [!NOTE] Responses include a maximum of 3000 files. The paginated response - * > returns 30 files per page by default. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response - * will include `body`. This is the default if you do not pass any specific media - * type. - * - **`application/vnd.github.text+json`**: Returns a text only representation of - * the markdown body. Response will include `body_text`. - * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's - * markdown. Response will include `body_html`. - * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML - * representations. Response will include `body`, `body_text`, and `body_html`. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const pullListFilesResponse of client.repos.pulls.listFiles( - * 0, - * { owner: 'owner', repo: 'repo' }, - * )) { - * // ... - * } - * ``` - */ - listFiles(pullNumber, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.getAPIList(path`/repos/${owner}/${repo}/pulls/${pullNumber}/files`, NumberedPage, { query, ...options }); + return makeFile([await value.arrayBuffer()], value.name); + } + if (isResponseLike(value)) { + const blob = await value.blob(); + name || (name = new URL(value.url).pathname.split(/[\\/]/).pop()); + return makeFile(await getBytes(blob), name, options); + } + const parts = await getBytes(value); + name || (name = getName(value)); + if (!options?.type) { + const type = parts.find((part) => typeof part === "object" && "type" in part && part.type); + if (typeof type === "string") { + options = { ...options, type }; } - /** - * Updates the pull request branch with the latest upstream changes by merging HEAD - * from the base branch into the pull request branch. Note: If making a request on - * behalf of a GitHub App you must also have permissions to write the contents of - * the head repository. - * - * @example - * ```ts - * const response = await client.repos.pulls.updateBranch(0, { - * owner: 'owner', - * repo: 'repo', - * expected_head_sha: - * '6dcb09b5b57875f334f61aebed695e2e4193db5e', - * }); - * ``` - */ - updateBranch(pullNumber, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...body } = params ?? {}; - return this._client.put(path`/repos/${owner}/${repo}/pulls/${pullNumber}/update-branch`, { - body, - ...options - }); + } + return makeFile(parts, name, options); +} +async function getBytes(value) { + let parts = []; + if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. + value instanceof ArrayBuffer) { + parts.push(value); + } else if (isBlobLike(value)) { + parts.push(value instanceof Blob ? value : await value.arrayBuffer()); + } else if (isAsyncIterable(value)) { + for await (const chunk of value) { + parts.push(...await getBytes(chunk)); } + } else { + const constructor = value?.constructor?.name; + throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError(value)}`); } - BasePulls2._key = Object.freeze(["repos", "pulls"]); - return BasePulls2; -})(); + return parts; +} +function propsForError(value) { + if (typeof value !== "object" || value === null) + return ""; + const props = Object.getOwnPropertyNames(value); + return `; props: [${props.map((p) => `"${p}"`).join(", ")}]`; +} -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/utils/uuid.mjs -var uuid4 = function() { - const { crypto: crypto2 } = globalThis; - if (crypto2?.randomUUID) { - uuid4 = crypto2.randomUUID.bind(crypto2); - return crypto2.randomUUID(); +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/core/resource.mjs +var APIResource = class { + constructor(client) { + this._client = client; } - const u8 = new Uint8Array(1); - const randomByte = crypto2 ? () => crypto2.getRandomValues(u8)[0] : () => Math.random() * 255 & 255; - return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16)); }; -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/utils/sleep.mjs -var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/version.mjs -var VERSION = "0.25.1"; - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/detect-platform.mjs -function getDetectedPlatform() { - if (typeof Deno !== "undefined" && Deno.build != null) { - return "deno"; - } - if (typeof EdgeRuntime !== "undefined") { - return "edge"; - } - if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") { - return "node"; - } - return "unknown"; +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/path.mjs +function encodeURIPath(str) { + return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); } -var getPlatformProperties = () => { - const detectedPlatform = getDetectedPlatform(); - if (detectedPlatform === "deno") { - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION, - "X-Stainless-OS": normalizePlatform(Deno.build.os), - "X-Stainless-Arch": normalizeArch(Deno.build.arch), - "X-Stainless-Runtime": "deno", - "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown" - }; +var EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); +var createPathTagFunction = (pathEncoder = encodeURIPath) => function path7(statics, ...params) { + if (statics.length === 1) + return statics[0]; + let postPath = false; + const invalidSegments = []; + const path8 = statics.reduce((previousValue, currentValue, index) => { + if (/[?#]/.test(currentValue)) { + postPath = true; + } + const value = params[index]; + let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value); + if (index !== params.length && (value == null || typeof value === "object" && // handle values from other realms + value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY)?.toString)) { + encoded = value + ""; + invalidSegments.push({ + start: previousValue.length + currentValue.length, + length: encoded.length, + error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter` + }); + } + return previousValue + currentValue + (index === params.length ? "" : encoded); + }, ""); + const pathOnly = path8.split(/[?#]/, 1)[0]; + const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; + let match; + while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) { + invalidSegments.push({ + start: match.index, + length: match[0].length, + error: `Value "${match[0]}" can't be safely passed as a path parameter` + }); } - if (typeof EdgeRuntime !== "undefined") { - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION, - "X-Stainless-OS": "Unknown", - "X-Stainless-Arch": `other:${EdgeRuntime}`, - "X-Stainless-Runtime": "edge", - "X-Stainless-Runtime-Version": globalThis.process.version - }; + invalidSegments.sort((a, b) => a.start - b.start); + if (invalidSegments.length > 0) { + let lastEnd = 0; + const underline = invalidSegments.reduce((acc, segment) => { + const spaces = " ".repeat(segment.start - lastEnd); + const arrows = "^".repeat(segment.length); + lastEnd = segment.start + segment.length; + return acc + spaces + arrows; + }, ""); + throw new StainlessError(`Path parameters result in path with invalid segments: +${invalidSegments.map((e) => e.error).join("\n")} +${path8} +${underline}`); } - if (detectedPlatform === "node") { - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION, - "X-Stainless-OS": normalizePlatform(globalThis.process.platform ?? "unknown"), - "X-Stainless-Arch": normalizeArch(globalThis.process.arch ?? "unknown"), - "X-Stainless-Runtime": "node", - "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown" - }; + return path8; +}; +var path = /* @__PURE__ */ createPathTagFunction(encodeURIPath); + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/builds/diagnostics.mjs +var Diagnostics = class extends APIResource { + /** + * Get the list of diagnostics for a given build. + * + * If no language targets are specified, diagnostics for all languages are + * returned. + */ + list(buildID, query = {}, options) { + return this._client.getAPIList(path`/v0/builds/${buildID}/diagnostics`, Page, { + query, + ...options + }); } - const browserInfo = getBrowserInfo(); - if (browserInfo) { - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION, - "X-Stainless-OS": "Unknown", - "X-Stainless-Arch": "unknown", - "X-Stainless-Runtime": `browser:${browserInfo.browser}`, - "X-Stainless-Runtime-Version": browserInfo.version - }; +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/builds/target-outputs.mjs +var TargetOutputs = class extends APIResource { + /** + * Retrieve a method to download an output for a given build target. + * + * If the requested type of output is `source`, and the requested output method is + * `url`, a download link to a tarball of the source files is returned. If the + * requested output method is `git`, a Git remote, ref, and access token (if + * necessary) is returned. + * + * Otherwise, the possible types of outputs are specific to the requested target, + * and the output method _must_ be `url`. See the documentation for `type` for more + * information. + */ + retrieve(query, options) { + return this._client.get("/v0/build_target_outputs", { query, ...options }); } - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION, - "X-Stainless-OS": "Unknown", - "X-Stainless-Arch": "unknown", - "X-Stainless-Runtime": "unknown", - "X-Stainless-Runtime-Version": "unknown" - }; }; -function getBrowserInfo() { - if (typeof navigator === "undefined" || !navigator) { - return null; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/builds/builds.mjs +var Builds = class extends APIResource { + constructor() { + super(...arguments); + this.diagnostics = new Diagnostics(this._client); + this.targetOutputs = new TargetOutputs(this._client); } - const browserPatterns = [ - { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ } - ]; - for (const { key, pattern } of browserPatterns) { - const match = pattern.exec(navigator.userAgent); - if (match) { - const major = match[1] || 0; - const minor = match[2] || 0; - const patch = match[3] || 0; - return { browser: key, version: `${major}.${minor}.${patch}` }; - } + /** + * Create a build, on top of a project branch, against a given input revision. + * + * The project branch will be modified so that its latest set of config files + * points to the one specified by the input revision. + */ + create(params, options) { + const { project = this._client.project, ...body } = params; + return this._client.post("/v0/builds", { body: { project, ...body }, ...options }); } - return null; -} -var normalizeArch = (arch) => { - if (arch === "x32") - return "x32"; - if (arch === "x86_64" || arch === "x64") - return "x64"; - if (arch === "arm") - return "arm"; - if (arch === "aarch64" || arch === "arm64") - return "arm64"; - if (arch) - return `other:${arch}`; - return "unknown"; -}; -var normalizePlatform = (platform) => { - platform = platform.toLowerCase(); - if (platform.includes("ios")) - return "iOS"; - if (platform === "android") - return "Android"; - if (platform === "darwin") - return "MacOS"; - if (platform === "win32") - return "Windows"; - if (platform === "freebsd") - return "FreeBSD"; - if (platform === "openbsd") - return "OpenBSD"; - if (platform === "linux") - return "Linux"; - if (platform) - return `Other:${platform}`; - return "Unknown"; -}; -var _platformHeaders; -var getPlatformHeaders = () => { - return _platformHeaders ?? (_platformHeaders = getPlatformProperties()); -}; - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/shims.mjs -function getDefaultFetch() { - if (typeof fetch !== "undefined") { - return fetch; + /** + * Retrieve a build by its ID. + */ + retrieve(buildID, options) { + return this._client.get(path`/v0/builds/${buildID}`, options); } - throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new GitHub({ fetch })` or polyfill the global, `globalThis.fetch = fetch`"); -} -function makeReadableStream(...args) { - const ReadableStream = globalThis.ReadableStream; - if (typeof ReadableStream === "undefined") { - throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`"); + /** + * List user-triggered builds for a given project. + * + * An optional revision can be specified to filter by config commit SHA, or hashes + * of file contents. + */ + list(params = {}, options) { + const { project = this._client.project, ...query } = params ?? {}; + return this._client.getAPIList("/v0/builds", Page, { query: { project, ...query }, ...options }); } - return new ReadableStream(...args); -} -function ReadableStreamFrom(iterable) { - let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); - return makeReadableStream({ - start() { - }, - async pull(controller) { - const { done, value } = await iter.next(); - if (done) { - controller.close(); - } else { - controller.enqueue(value); - } - }, - async cancel() { - await iter.return?.(); - } - }); -} -async function CancelReadableStream(stream) { - if (stream === null || typeof stream !== "object") - return; - if (stream[Symbol.asyncIterator]) { - await stream[Symbol.asyncIterator]().return?.(); - return; + /** + * Create two builds whose outputs can be directly compared with each other. + * + * Created builds _modify_ their project branches so that their latest sets of + * config files point to the ones specified by the input revision. + * + * This endpoint is useful because a build has more inputs than the set of config + * files it uses, so comparing two builds directly may return spurious differences. + * Builds made via this endpoint are guaranteed to have differences arising from + * the set of config files, and any custom code. + */ + compare(params, options) { + const { project = this._client.project, ...body } = params; + return this._client.post("/v0/builds/compare", { body: { project, ...body }, ...options }); } - const reader = stream.getReader(); - const cancelPromise = reader.cancel(); - reader.releaseLock(); - await cancelPromise; -} - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/request-options.mjs -var FallbackEncoder = ({ headers, body }) => { - return { - bodyHeaders: { - "content-type": "application/json" - }, - body: JSON.stringify(body) - }; }; +Builds.Diagnostics = Diagnostics; +Builds.TargetOutputs = TargetOutputs; -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/qs/formats.mjs -var default_format = "RFC3986"; -var default_formatter = (v) => String(v); -var formatters = { - RFC1738: (v) => String(v).replace(/%20/g, "+"), - RFC3986: default_formatter +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/orgs.mjs +var Orgs = class extends APIResource { + /** + * Retrieve an organization by name. + */ + retrieve(org, options) { + return this._client.get(path`/v0/orgs/${org}`, options); + } + /** + * List organizations accessible to the current authentication method. + */ + list(options) { + return this._client.get("/v0/orgs", options); + } }; -var RFC1738 = "RFC1738"; -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/qs/utils.mjs -var has = (obj, key) => (has = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has(obj, key)); -var hex_table = /* @__PURE__ */ (() => { - const array = []; - for (let i = 0; i < 256; ++i) { - array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase()); - } - return array; -})(); -var limit = 1024; -var encode = (str, _defaultEncoder, charset, _kind, format) => { - if (str.length === 0) { - return str; +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/projects/branches.mjs +var Branches = class extends APIResource { + /** + * Create a new branch for a project. + * + * The branch inherits the config files from the revision pointed to by the + * `branch_from` parameter. In addition, if the revision is a branch name, the + * branch will also inherit custom code changes from that branch. + */ + create(params, options) { + const { project = this._client.project, ...body } = params; + return this._client.post(path`/v0/projects/${project}/branches`, { body, ...options }); } - let string = str; - if (typeof str === "symbol") { - string = Symbol.prototype.toString.call(str); - } else if (typeof str !== "string") { - string = String(str); + /** + * Retrieve a project branch by name. + */ + retrieve(branch, params = {}, options) { + const { project = this._client.project } = params ?? {}; + return this._client.get(path`/v0/projects/${project}/branches/${branch}`, options); } - if (charset === "iso-8859-1") { - return escape(string).replace(/%u[0-9a-f]{4}/gi, function($0) { - return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; + /** + * Retrieve a project branch by name. + */ + list(params = {}, options) { + const { project = this._client.project, ...query } = params ?? {}; + return this._client.getAPIList(path`/v0/projects/${project}/branches`, Page, { + query, + ...options }); } - let out = ""; - for (let j = 0; j < string.length; j += limit) { - const segment = string.length >= limit ? string.slice(j, j + limit) : string; - const arr = []; - for (let i = 0; i < segment.length; ++i) { - let c = segment.charCodeAt(i); - if (c === 45 || // - - c === 46 || // . - c === 95 || // _ - c === 126 || // ~ - c >= 48 && c <= 57 || // 0-9 - c >= 65 && c <= 90 || // a-z - c >= 97 && c <= 122 || // A-Z - format === RFC1738 && (c === 40 || c === 41)) { - arr[arr.length] = segment.charAt(i); - continue; - } - if (c < 128) { - arr[arr.length] = hex_table[c]; - continue; - } - if (c < 2048) { - arr[arr.length] = hex_table[192 | c >> 6] + hex_table[128 | c & 63]; - continue; - } - if (c < 55296 || c >= 57344) { - arr[arr.length] = hex_table[224 | c >> 12] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63]; - continue; - } - i += 1; - c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023); - arr[arr.length] = hex_table[240 | c >> 18] + hex_table[128 | c >> 12 & 63] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63]; - } - out += arr.join(""); + /** + * Delete a project branch by name. + */ + delete(branch, params = {}, options) { + const { project = this._client.project } = params ?? {}; + return this._client.delete(path`/v0/projects/${project}/branches/${branch}`, options); } - return out; -}; -function is_buffer(obj) { - if (!obj || typeof obj !== "object") { - return false; + /** + * Rebase a project branch. + * + * The branch is rebased onto the `base` branch or commit SHA, inheriting any + * config and custom code changes. + */ + rebase(branch, params = {}, options) { + const { project = this._client.project, base } = params ?? {}; + return this._client.put(path`/v0/projects/${project}/branches/${branch}/rebase`, { + query: { base }, + ...options + }); } - return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); -} -function maybe_map(val, fn) { - if (isArray(val)) { - const mapped = []; - for (let i = 0; i < val.length; i += 1) { - mapped.push(fn(val[i])); - } - return mapped; + /** + * Reset a project branch. + * + * If `branch` === `main`, the branch is reset to `target_config_sha`. Otherwise, + * the branch is reset to `main`. + */ + reset(branch, params = {}, options) { + const { project = this._client.project, target_config_sha } = params ?? {}; + return this._client.put(path`/v0/projects/${project}/branches/${branch}/reset`, { + query: { target_config_sha }, + ...options + }); } - return fn(val); -} +}; -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/qs/stringify.mjs -var array_prefix_generators = { - brackets(prefix) { - return String(prefix) + "[]"; - }, - comma: "comma", - indices(prefix, key) { - return String(prefix) + "[" + key + "]"; - }, - repeat(prefix) { - return String(prefix); +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/projects/configs.mjs +var Configs = class extends APIResource { + /** + * Retrieve the configuration files for a given project. + */ + retrieve(params = {}, options) { + const { project = this._client.project, ...query } = params ?? {}; + return this._client.get(path`/v0/projects/${project}/configs`, { query, ...options }); + } + /** + * Generate suggestions for changes to config files based on an OpenAPI spec. + */ + guess(params, options) { + const { project = this._client.project, ...body } = params; + return this._client.post(path`/v0/projects/${project}/configs/guess`, { body, ...options }); } }; -var push_to_array = function(arr, value_or_array) { - Array.prototype.push.apply(arr, isArray(value_or_array) ? value_or_array : [value_or_array]); + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/projects/projects.mjs +var Projects = class extends APIResource { + constructor() { + super(...arguments); + this.branches = new Branches(this._client); + this.configs = new Configs(this._client); + } + /** + * Create a new project. + */ + create(body, options) { + return this._client.post("/v0/projects", { body, ...options }); + } + /** + * Retrieve a project by name. + */ + retrieve(params = {}, options) { + const { project = this._client.project } = params ?? {}; + return this._client.get(path`/v0/projects/${project}`, options); + } + /** + * Update a project's properties. + */ + update(params = {}, options) { + const { project = this._client.project, ...body } = params ?? {}; + return this._client.patch(path`/v0/projects/${project}`, { body, ...options }); + } + /** + * List projects in an organization, from oldest to newest. + */ + list(query = {}, options) { + return this._client.getAPIList("/v0/projects", Page, { query, ...options }); + } + /** + * Generates an AI commit message by comparing two git refs in the SDK repository. + */ + generateCommitMessage(params, options) { + const { project = this._client.project, target, ...body } = params; + return this._client.post(path`/v0/projects/${project}/generate_commit_message`, { + query: { target }, + body, + ...options + }); + } }; -var toISOString; -var defaults = { - addQueryPrefix: false, - allowDots: false, - allowEmptyArrays: false, - arrayFormat: "indices", - charset: "utf-8", - charsetSentinel: false, - delimiter: "&", - encode: true, - encodeDotInKeys: false, - encoder: encode, - encodeValuesOnly: false, - format: default_format, - formatter: default_formatter, - /** @deprecated */ - indices: false, - serializeDate(date) { - return (toISOString ?? (toISOString = Function.prototype.call.bind(Date.prototype.toISOString)))(date); - }, - skipNulls: false, - strictNullHandling: false +Projects.Branches = Branches; +Projects.Configs = Configs; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/user.mjs +var User = class extends APIResource { + /** + * Retrieve the currently authenticated user's information. + */ + retrieve(options) { + return this._client.get("/v0/user", options); + } }; -function is_non_nullish_primitive(v) { - return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint"; -} -var sentinel = {}; -function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { - let obj = object; - let tmp_sc = sideChannel; - let step = 0; - let find_flag = false; - while ((tmp_sc = tmp_sc.get(sentinel)) !== void 0 && !find_flag) { - const pos = tmp_sc.get(object); - step += 1; - if (typeof pos !== "undefined") { - if (pos === step) { - throw new RangeError("Cyclic object value"); - } else { - find_flag = true; - } - } - if (typeof tmp_sc.get(sentinel) === "undefined") { - step = 0; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/headers.mjs +var brand_privateNullableHeaders = /* @__PURE__ */ Symbol("brand.privateNullableHeaders"); +function* iterateHeaders(headers) { + if (!headers) + return; + if (brand_privateNullableHeaders in headers) { + const { values, nulls } = headers; + yield* values.entries(); + for (const name of nulls) { + yield [name, null]; } + return; } - if (typeof filter === "function") { - obj = filter(prefix, obj); - } else if (obj instanceof Date) { - obj = serializeDate?.(obj); - } else if (generateArrayPrefix === "comma" && isArray(obj)) { - obj = maybe_map(obj, function(value) { - if (value instanceof Date) { - return serializeDate?.(value); - } - return value; - }); + let shouldClear = false; + let iter; + if (headers instanceof Headers) { + iter = headers.entries(); + } else if (isReadonlyArray(headers)) { + iter = headers; + } else { + shouldClear = true; + iter = Object.entries(headers ?? {}); } - if (obj === null) { - if (strictNullHandling) { - return encoder && !encodeValuesOnly ? ( - // @ts-expect-error - encoder(prefix, defaults.encoder, charset, "key", format) - ) : prefix; + for (let row of iter) { + const name = row[0]; + if (typeof name !== "string") + throw new TypeError("expected header name to be a string"); + const values = isReadonlyArray(row[1]) ? row[1] : [row[1]]; + let didClear = false; + for (const value of values) { + if (value === void 0) + continue; + if (shouldClear && !didClear) { + didClear = true; + yield [name, null]; + } + yield [name, value]; } - obj = ""; } - if (is_non_nullish_primitive(obj) || is_buffer(obj)) { - if (encoder) { - const key_value = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, "key", format); - return [ - formatter?.(key_value) + "=" + // @ts-expect-error - formatter?.(encoder(obj, defaults.encoder, charset, "value", format)) - ]; +} +var buildHeaders = (newHeaders) => { + const targetHeaders = new Headers(); + const nullHeaders = /* @__PURE__ */ new Set(); + for (const headers of newHeaders) { + const seenHeaders = /* @__PURE__ */ new Set(); + for (const [name, value] of iterateHeaders(headers)) { + const lowerName = name.toLowerCase(); + if (!seenHeaders.has(lowerName)) { + targetHeaders.delete(name); + seenHeaders.add(lowerName); + } + if (value === null) { + targetHeaders.delete(name); + nullHeaders.add(lowerName); + } else { + targetHeaders.append(name, value); + nullHeaders.delete(lowerName); + } } - return [formatter?.(prefix) + "=" + formatter?.(String(obj))]; } - const values = []; - if (typeof obj === "undefined") { - return values; + return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders }; +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/env.mjs +var readEnv = (env) => { + if (typeof globalThis.process !== "undefined") { + return globalThis.process.env?.[env]?.trim() ?? void 0; } - let obj_keys; - if (generateArrayPrefix === "comma" && isArray(obj)) { - if (encodeValuesOnly && encoder) { - obj = maybe_map(obj, encoder); - } - obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; - } else if (isArray(filter)) { - obj_keys = filter; - } else { - const keys = Object.keys(obj); - obj_keys = sort ? keys.sort(sort) : keys; + if (typeof globalThis.Deno !== "undefined") { + return globalThis.Deno.env?.get?.(env)?.trim(); } - const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix); - const adjusted_prefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix; - if (allowEmptyArrays && isArray(obj) && obj.length === 0) { - return adjusted_prefix + "[]"; + return void 0; +}; + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/lib/unwrap.mjs +async function unwrapFile(value) { + if (value === null) { + return null; } - for (let j = 0; j < obj_keys.length; ++j) { - const key = obj_keys[j]; - const value = ( - // @ts-ignore - typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key] - ); - if (skipNulls && value === null) { - continue; - } - const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key; - const key_prefix = isArray(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]"); - sideChannel.set(object, step); - const valueSideChannel = /* @__PURE__ */ new WeakMap(); - valueSideChannel.set(sentinel, sideChannel); - push_to_array(values, inner_stringify( - value, - key_prefix, - generateArrayPrefix, - commaRoundTrip, - allowEmptyArrays, - strictNullHandling, - skipNulls, - encodeDotInKeys, - // @ts-ignore - generateArrayPrefix === "comma" && encodeValuesOnly && isArray(obj) ? null : encoder, - filter, - sort, - allowDots, - serializeDate, - format, - formatter, - encodeValuesOnly, - charset, - valueSideChannel - )); + if (value.type === "content") { + return value.content; } - return values; + const response = await fetch(value.url); + return response.text(); } -function normalize_stringify_options(opts = defaults) { - if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") { - throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); + +// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/client.mjs +var _Stainless_instances; +var _a; +var _Stainless_encoder; +var _Stainless_baseURLOverridden; +var environments = { + production: "https://api.stainless.com", + staging: "https://staging.stainless.com" +}; +var Stainless = class { + /** + * API Client for interfacing with the Stainless API. + * + * @param {string | null | undefined} [opts.apiKey=process.env['STAINLESS_API_KEY'] ?? null] + * @param {string | null | undefined} [opts.project] + * @param {Environment} [opts.environment=production] - Specifies the environment URL to use for the API. + * @param {string} [opts.baseURL=process.env['STAINLESS_BASE_URL'] ?? https://api.stainless.com] - Override the default base URL for the API. + * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. + * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. + */ + constructor({ baseURL = readEnv("STAINLESS_BASE_URL"), apiKey = readEnv("STAINLESS_API_KEY") ?? null, project = null, ...opts } = {}) { + _Stainless_instances.add(this); + _Stainless_encoder.set(this, void 0); + this.projects = new Projects(this); + this.builds = new Builds(this); + this.orgs = new Orgs(this); + this.user = new User(this); + const options = { + apiKey, + project, + ...opts, + baseURL, + environment: opts.environment ?? "production" + }; + if (baseURL && opts.environment) { + throw new StainlessError("Ambiguous URL; The `baseURL` option (or STAINLESS_BASE_URL env var) and the `environment` option are given. If you want to use the environment you must pass baseURL: null"); + } + this.baseURL = options.baseURL || environments[options.environment || "production"]; + this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT; + this.logger = options.logger ?? console; + const defaultLogLevel = "warn"; + this.logLevel = defaultLogLevel; + this.logLevel = parseLogLevel(options.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel(readEnv("STAINLESS_LOG"), "process.env['STAINLESS_LOG']", this) ?? defaultLogLevel; + this.fetchOptions = options.fetchOptions; + this.maxRetries = options.maxRetries ?? 2; + this.fetch = options.fetch ?? getDefaultFetch(); + __classPrivateFieldSet(this, _Stainless_encoder, FallbackEncoder, "f"); + this._options = options; + this.apiKey = apiKey; + this.project = project; } - if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") { - throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided"); + /** + * Create a new client instance re-using the same options given to the current client with optional overriding. + */ + withOptions(options) { + const client = new this.constructor({ + ...this._options, + environment: options.environment ? options.environment : void 0, + baseURL: options.environment ? void 0 : this.baseURL, + maxRetries: this.maxRetries, + timeout: this.timeout, + logger: this.logger, + logLevel: this.logLevel, + fetch: this.fetch, + fetchOptions: this.fetchOptions, + apiKey: this.apiKey, + project: this.project, + ...options + }); + return client; } - if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") { - throw new TypeError("Encoder has to be a function."); + defaultQuery() { + return this._options.defaultQuery; } - const charset = opts.charset || defaults.charset; - if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { - throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); + validateHeaders({ values, nulls }) { + if (this.apiKey && values.get("authorization")) { + return; + } + if (nulls.has("authorization")) { + return; + } + throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "Authorization" headers to be explicitly omitted'); } - let format = default_format; - if (typeof opts.format !== "undefined") { - if (!has(formatters, opts.format)) { - throw new TypeError("Unknown format option provided."); + async authHeaders(opts) { + if (this.apiKey == null) { + return void 0; } - format = opts.format; + return buildHeaders([{ Authorization: `Bearer ${this.apiKey}` }]); } - const formatter = formatters[format]; - let filter = defaults.filter; - if (typeof opts.filter === "function" || isArray(opts.filter)) { - filter = opts.filter; + stringifyQuery(query) { + return stringifyQuery(query); } - let arrayFormat; - if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) { - arrayFormat = opts.arrayFormat; - } else if ("indices" in opts) { - arrayFormat = opts.indices ? "indices" : "repeat"; - } else { - arrayFormat = defaults.arrayFormat; + getUserAgent() { + return `${this.constructor.name}/JS ${VERSION}`; } - if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") { - throw new TypeError("`commaRoundTrip` must be a boolean, or absent"); + defaultIdempotencyKey() { + return `stainless-node-retry-${uuid4()}`; } - const allowDots = typeof opts.allowDots === "undefined" ? !!opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; - return { - addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix, - // @ts-ignore - allowDots, - allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, - arrayFormat, - charset, - charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel, - commaRoundTrip: !!opts.commaRoundTrip, - delimiter: typeof opts.delimiter === "undefined" ? defaults.delimiter : opts.delimiter, - encode: typeof opts.encode === "boolean" ? opts.encode : defaults.encode, - encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults.encodeDotInKeys, - encoder: typeof opts.encoder === "function" ? opts.encoder : defaults.encoder, - encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults.encodeValuesOnly, - filter, - format, - formatter, - serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults.serializeDate, - skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults.skipNulls, - // @ts-ignore - sort: typeof opts.sort === "function" ? opts.sort : null, - strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling - }; -} -function stringify(object, opts = {}) { - let obj = object; - const options = normalize_stringify_options(opts); - let obj_keys; - let filter; - if (typeof options.filter === "function") { - filter = options.filter; - obj = filter("", obj); - } else if (isArray(options.filter)) { - filter = options.filter; - obj_keys = filter; + makeStatusError(status, error, message, headers) { + return APIError.generate(status, error, message, headers); } - const keys = []; - if (typeof obj !== "object" || obj === null) { - return ""; + buildURL(path7, query, defaultBaseURL) { + const baseURL = !__classPrivateFieldGet(this, _Stainless_instances, "m", _Stainless_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL; + const url = isAbsoluteURL(path7) ? new URL(path7) : new URL(baseURL + (baseURL.endsWith("/") && path7.startsWith("/") ? path7.slice(1) : path7)); + const defaultQuery = this.defaultQuery(); + if (!isEmptyObj(defaultQuery)) { + query = { ...defaultQuery, ...query }; + } + if (typeof query === "object" && query && !Array.isArray(query)) { + url.search = this.stringifyQuery(query); + } + return url.toString(); } - const generateArrayPrefix = array_prefix_generators[options.arrayFormat]; - const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip; - if (!obj_keys) { - obj_keys = Object.keys(obj); + /** + * Used as a callback for mutating the given `FinalRequestOptions` object. + */ + async prepareOptions(options) { } - if (options.sort) { - obj_keys.sort(options.sort); + /** + * Used as a callback for mutating the given `RequestInit` object. + * + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. + */ + async prepareRequest(request, { url, options }) { } - const sideChannel = /* @__PURE__ */ new WeakMap(); - for (let i = 0; i < obj_keys.length; ++i) { - const key = obj_keys[i]; - if (options.skipNulls && obj[key] === null) { - continue; - } - push_to_array(keys, inner_stringify( - obj[key], - key, - // @ts-expect-error - generateArrayPrefix, - commaRoundTrip, - options.allowEmptyArrays, - options.strictNullHandling, - options.skipNulls, - options.encodeDotInKeys, - options.encode ? options.encoder : null, - options.filter, - options.sort, - options.allowDots, - options.serializeDate, - options.format, - options.formatter, - options.encodeValuesOnly, - options.charset, - sideChannel - )); + get(path7, opts) { + return this.methodRequest("get", path7, opts); } - const joined = keys.join(options.delimiter); - let prefix = options.addQueryPrefix === true ? "?" : ""; - if (options.charsetSentinel) { - if (options.charset === "iso-8859-1") { - prefix += "utf8=%26%2310003%3B&"; - } else { - prefix += "utf8=%E2%9C%93&"; - } + post(path7, opts) { + return this.methodRequest("post", path7, opts); } - return joined.length > 0 ? prefix + joined : ""; -} - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/resources/apps/installations/installations.mjs -var BaseInstallations = /* @__PURE__ */ (() => { - class BaseInstallations4 extends APIResource { - /** - * Enables an authenticated GitHub App to find an installation's information using - * the installation id. - * - * You must use a - * [JWT](https://docs.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) - * to access this endpoint. - * - * @example - * ```ts - * const installation = - * await client.apps.installations.retrieve(0); - * ``` - */ - retrieve(installationID, options) { - return this._client.get(path`/app/installations/${installationID}`, options); + patch(path7, opts) { + return this.methodRequest("patch", path7, opts); + } + put(path7, opts) { + return this.methodRequest("put", path7, opts); + } + delete(path7, opts) { + return this.methodRequest("delete", path7, opts); + } + methodRequest(method, path7, opts) { + return this.request(Promise.resolve(opts).then((opts2) => { + return { method, path: path7, ...opts2 }; + })); + } + request(options, remainingRetries = null) { + return new APIPromise(this, this.makeRequest(options, remainingRetries, void 0)); + } + async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { + const options = await optionsInput; + const maxRetries = options.maxRetries ?? this.maxRetries; + if (retriesRemaining == null) { + retriesRemaining = maxRetries; } - /** - * The permissions the installation has are included under the `permissions` key. - * - * You must use a - * [JWT](https://docs.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) - * to access this endpoint. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const installation of client.apps.installations.list()) { - * // ... - * } - * ``` - */ - list(query = {}, options) { - return this._client.getAPIList("/app/installations", NumberedPage, { - query, - ...options - }); + await this.prepareOptions(options); + const { req, url, timeout } = await this.buildRequest(options, { + retryCount: maxRetries - retriesRemaining + }); + await this.prepareRequest(req, { url, options }); + const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0"); + const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`; + const startTime = Date.now(); + loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({ + retryOfRequestLogID, + method: options.method, + url, + options, + headers: req.headers + })); + if (options.signal?.aborted) { + throw new APIUserAbortError(); } - /** - * Uninstalls a GitHub App on a user, organization, or enterprise account. If you - * prefer to temporarily suspend an app's access to your account's resources, then - * we recommend the - * "[Suspend an app installation](https://docs.github.com/rest/apps/apps#suspend-an-app-installation)" - * endpoint. - * - * You must use a - * [JWT](https://docs.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) - * to access this endpoint. - * - * @example - * ```ts - * await client.apps.installations.delete(0); - * ``` - */ - delete(installationID, options) { - return this._client.delete(path`/app/installations/${installationID}`, { - ...options, - headers: buildHeaders([{ Accept: "*/*" }, options?.headers]) - }); + const controller = new AbortController(); + const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError); + const headersTime = Date.now(); + if (response instanceof globalThis.Error) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + if (options.signal?.aborted) { + throw new APIUserAbortError(); + } + const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : "")); + if (retriesRemaining) { + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`); + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); + } + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`); + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + if (isTimeout) { + throw new APIConnectionTimeoutError(); + } + throw new APIConnectionError({ cause: response }); } - /** - * Creates an installation access token that enables a GitHub App to make - * authenticated API requests for the app's installation on an organization or - * individual account. Installation tokens expire one hour from the time you create - * them. Using an expired token produces a status code of `401 - Unauthorized`, and - * requires creating a new installation token. By default the installation token - * has access to all repositories that the installation can access. - * - * Optionally, you can use the `repositories` or `repository_ids` body parameters - * to specify individual repositories that the installation access token can - * access. If you don't use `repositories` or `repository_ids` to grant access to - * specific repositories, the installation access token will have access to all - * repositories that the installation was granted access to. The installation - * access token cannot be granted access to repositories that the installation was - * not granted access to. Up to 500 repositories can be listed in this manner. - * - * Optionally, use the `permissions` body parameter to specify the permissions that - * the installation access token should have. If `permissions` is not specified, - * the installation access token will have all of the permissions that were granted - * to the app. The installation access token cannot be granted permissions that the - * app was not granted. - * - * You must use a - * [JWT](https://docs.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) - * to access this endpoint. - * - * @example - * ```ts - * const response = - * await client.apps.installations.createAccessToken(0, { - * permissions: { issues: 'write', contents: 'read' }, - * repositories: ['Hello-World'], - * }); - * ``` - */ - createAccessToken(installationID, body = {}, options) { - return this._client.post(path`/app/installations/${installationID}/access_tokens`, { body, ...options }); + const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`; + if (!response.ok) { + const shouldRetry = await this.shouldRetry(response); + if (retriesRemaining && shouldRetry) { + const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`; + await CancelReadableStream(response.body); + loggerFor(this).info(`${responseInfo} - ${retryMessage2}`); + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); + } + const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; + loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + const errText = await response.text().catch((err2) => castToError(err2).message); + const errJSON = safeJSON(errText); + const errMessage = errJSON ? void 0 : errText; + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + message: errMessage, + durationMs: Date.now() - startTime + })); + const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); + throw err; } + loggerFor(this).info(responseInfo); + loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; } - BaseInstallations4._key = Object.freeze([ - "apps", - "installations" - ]); - return BaseInstallations4; -})(); - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/resources/orgs/orgs.mjs -var BaseOrgs = /* @__PURE__ */ (() => { - class BaseOrgs3 extends APIResource { - /** - * Gets information about an organization. - * - * When the value of `two_factor_requirement_enabled` is `true`, the organization - * requires all members, billing managers, outside collaborators, guest - * collaborators, repository collaborators, or everyone with access to any - * repository within the organization to enable - * [two-factor authentication](https://docs.github.com/articles/securing-your-account-with-two-factor-authentication-2fa/). - * - * To see the full details about an organization, the authenticated user must be an - * organization owner. - * - * OAuth app tokens and personal access tokens (classic) need the `admin:org` scope - * to see the full details about an organization. - * - * To see information about an organization's GitHub plan, GitHub Apps need the - * `Organization plan` permission. - * - * @example - * ```ts - * const org = await client.orgs.retrieve('org'); - * ``` - */ - retrieve(org, options) { - return this._client.get(path`/orgs/${org}`, options); + getAPIList(path7, Page2, opts) { + return this.requestAPIList(Page2, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path7, ...opts2 })) : { method: "get", path: path7, ...opts }); + } + requestAPIList(Page2, options) { + const request = this.makeRequest(options, null, void 0); + return new PagePromise(this, request, Page2); + } + async fetchWithTimeout(url, init, ms, controller) { + const { signal, method, ...options } = init || {}; + const abort = this._makeAbort(controller); + if (signal) + signal.addEventListener("abort", abort, { once: true }); + const timeout = setTimeout(abort, ms); + const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body; + const fetchOptions = { + signal: controller.signal, + ...isReadableBody ? { duplex: "half" } : {}, + method: "GET", + ...options + }; + if (method) { + fetchOptions.method = method.toUpperCase(); } - /** - * > [!WARNING] > **Closing down notice:** GitHub will replace and discontinue - * > `members_allowed_repository_creation_type` in favor of more granular - * > permissions. The new input parameters are - * > `members_can_create_public_repositories`, - * > `members_can_create_private_repositories` for all organizations and - * > `members_can_create_internal_repositories` for organizations associated with - * > an enterprise account using GitHub Enterprise Cloud or GitHub Enterprise - * > Server 2.20+. For more information, see the - * > [blog post](https://developer.github.com/changes/2019-12-03-internal-visibility-changes). - * - * > [!WARNING] > **Closing down notice:** Code security product enablement for new - * > repositories through the organization API is closing down. Please use - * > [code security configurations](https://docs.github.com/rest/code-security/configurations#set-a-code-security-configuration-as-a-default-for-an-organization) - * > to set defaults instead. For more information on setting a default security - * > configuration, see the - * > [changelog](https://github.blog/changelog/2024-07-09-sunsetting-security-settings-defaults-parameters-in-the-organizations-rest-api/). - * - * Updates the organization's profile and member privileges. - * - * The authenticated user must be an organization owner to use this endpoint. - * - * OAuth app tokens and personal access tokens (classic) need the `admin:org` or - * `repo` scope to use this endpoint. - * - * @example - * ```ts - * const org = await client.orgs.update('org', { - * billing_email: 'mona@github.com', - * company: 'GitHub', - * default_repository_permission: 'read', - * description: 'GitHub, the company.', - * email: 'mona@github.com', - * location: 'San Francisco', - * members_allowed_repository_creation_type: 'all', - * members_can_create_repositories: true, - * name: 'github', - * twitter_username: 'github', - * }); - * ``` - */ - update(org, body = {}, options) { - return this._client.patch(path`/orgs/${org}`, { body, ...options }); - } - /** - * Deletes an organization and all its repositories. - * - * The organization login will be unavailable for 90 days after deletion. - * - * Please review the Terms of Service regarding account deletion before using this - * endpoint: - * - * https://docs.github.com/site-policy/github-terms/github-terms-of-service - * - * @example - * ```ts - * const org = await client.orgs.delete('org'); - * ``` - */ - delete(org, options) { - return this._client.delete(path`/orgs/${org}`, options); + try { + return await this.fetch.call(void 0, url, fetchOptions); + } finally { + clearTimeout(timeout); } - /** - * List a collection of artifact attestations with a given subject digest that are - * associated with repositories owned by an organization. - * - * The collection of attestations returned by this endpoint is filtered according - * to the authenticated user's permissions; if the authenticated user cannot read a - * repository, the attestations associated with that repository will not be - * included in the response. In addition, when using a fine-grained access token - * the `attestations:read` permission is required. - * - * **Please note:** in order to offer meaningful security benefits, an - * attestation's signature and timestamps **must** be cryptographically verified, - * and the identity of the attestation signer **must** be validated. Attestations - * can be verified using the - * [GitHub CLI `attestation verify` command](https://cli.github.com/manual/gh_attestation_verify). - * For more information, see - * [our guide on how to use artifact attestations to establish a build's provenance](https://docs.github.com/actions/security-guides/using-artifact-attestations-to-establish-provenance-for-builds). - * - * @example - * ```ts - * const response = await client.orgs.listAttestations( - * 'subject_digest', - * { org: 'org' }, - * ); - * ``` - */ - listAttestations(subjectDigest, params, options) { - const { org, ...query } = params; - return this._client.get(path`/orgs/${org}/attestations/${subjectDigest}`, { query, ...options }); + } + async shouldRetry(response) { + const shouldRetryHeader = response.headers.get("x-should-retry"); + if (shouldRetryHeader === "true") + return true; + if (shouldRetryHeader === "false") + return false; + if (response.status === 408) + return true; + if (response.status === 409) + return true; + if (response.status === 429) + return true; + if (response.status >= 500) + return true; + return false; + } + async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { + let timeoutMillis; + const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms"); + if (retryAfterMillisHeader) { + const timeoutMs = parseFloat(retryAfterMillisHeader); + if (!Number.isNaN(timeoutMs)) { + timeoutMillis = timeoutMs; + } } - /** - * > [!NOTE] This API is not built to serve real-time use cases. Depending on the - * > time of day, event latency can be anywhere from 30s to 6h. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const orgListEventsResponse of client.orgs.listEvents( - * 'org', - * )) { - * // ... - * } - * ``` - */ - listEvents(org, query = {}, options) { - return this._client.getAPIList(path`/orgs/${org}/events`, NumberedPage, { - query, - ...options - }); + const retryAfterHeader = responseHeaders?.get("retry-after"); + if (retryAfterHeader && !timeoutMillis) { + const timeoutSeconds = parseFloat(retryAfterHeader); + if (!Number.isNaN(timeoutSeconds)) { + timeoutMillis = timeoutSeconds * 1e3; + } else { + timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); + } } - /** - * The return hash contains `failed_at` and `failed_reason` fields which represent - * the time at which the invitation failed and the reason for the failure. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const orgListFailedInvitationsResponse of client.orgs.listFailedInvitations( - * 'org', - * )) { - * // ... - * } - * ``` - */ - listFailedInvitations(org, query = {}, options) { - return this._client.getAPIList(path`/orgs/${org}/failed_invitations`, NumberedPage, { query, ...options }); + if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1e3)) { + const maxRetries = options.maxRetries ?? this.maxRetries; + timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); } - /** - * Lists all GitHub Apps in an organization. The installation count includes all - * GitHub Apps installed on repositories in the organization. - * - * The authenticated user must be an organization owner to use this endpoint. - * - * OAuth app tokens and personal access tokens (classic) need the `admin:read` - * scope to use this endpoint. - * - * @example - * ```ts - * const response = await client.orgs.listInstallations('org'); - * ``` - */ - listInstallations(org, query = {}, options) { - return this._client.get(path`/orgs/${org}/installations`, { query, ...options }); + await sleep(timeoutMillis); + return this.makeRequest(options, retriesRemaining - 1, requestLogID); + } + calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { + const initialRetryDelay = 0.5; + const maxRetryDelay = 8; + const numRetries = maxRetries - retriesRemaining; + const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); + const jitter = 1 - Math.random() * 0.25; + return sleepSeconds * jitter * 1e3; + } + async buildRequest(inputOptions, { retryCount = 0 } = {}) { + const options = { ...inputOptions }; + const { method, path: path7, query, defaultBaseURL } = options; + const url = this.buildURL(path7, query, defaultBaseURL); + if ("timeout" in options) + validatePositiveInteger("timeout", options.timeout); + options.timeout = options.timeout ?? this.timeout; + const { bodyHeaders, body } = this.buildBody({ options }); + const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); + const req = { + method, + headers: reqHeaders, + ...options.signal && { signal: options.signal }, + ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" }, + ...body && { body }, + ...this.fetchOptions ?? {}, + ...options.fetchOptions ?? {} + }; + return { req, url, timeout: options.timeout }; + } + async buildHeaders({ options, method, bodyHeaders, retryCount }) { + let idempotencyHeaders = {}; + if (this.idempotencyHeader && method !== "get") { + if (!options.idempotencyKey) + options.idempotencyKey = this.defaultIdempotencyKey(); + idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; } - /** - * List issues in an organization assigned to the authenticated user. - * - * > [!NOTE] GitHub's REST API considers every pull request an issue, but not every - * > issue is a pull request. For this reason, "Issues" endpoints may return both - * > issues and pull requests in the response. You can identify pull requests by - * > the `pull_request` key. Be aware that the `id` of a pull request returned from - * > "Issues" endpoints will be an _issue id_. To find out the pull request id, use - * > the - * > "[List pull requests](https://docs.github.com/rest/pulls/pulls#list-pull-requests)" - * > endpoint. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response - * will include `body`. This is the default if you do not pass any specific media - * type. - * - **`application/vnd.github.text+json`**: Returns a text only representation of - * the markdown body. Response will include `body_text`. - * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's - * markdown. Response will include `body_html`. - * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML - * representations. Response will include `body`, `body_text`, and `body_html`. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const issue of client.orgs.listIssues('org')) { - * // ... - * } - * ``` - */ - listIssues(org, query = {}, options) { - return this._client.getAPIList(path`/orgs/${org}/issues`, NumberedPage, { - query, - ...options - }); + const headers = buildHeaders([ + idempotencyHeaders, + { + Accept: "application/json", + "User-Agent": this.getUserAgent(), + "X-Stainless-Retry-Count": String(retryCount), + ...options.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options.timeout / 1e3)) } : {}, + ...getPlatformHeaders() + }, + await this.authHeaders(options), + this._options.defaultHeaders, + bodyHeaders, + options.headers + ]); + this.validateHeaders(headers); + return headers.values; + } + _makeAbort(controller) { + return () => controller.abort(); + } + buildBody({ options: { body, headers: rawHeaders } }) { + if (!body) { + return { bodyHeaders: void 0, body: void 0 }; } - /** - * Lists repository security advisories for an organization. - * - * The authenticated user must be an owner or security manager for the organization - * to use this endpoint. - * - * OAuth app tokens and personal access tokens (classic) need the `repo` or - * `repository_advisories:write` scope to use this endpoint. - * - * @example - * ```ts - * const response = await client.orgs.listSecurityAdvisories( - * 'org', - * ); - * ``` - */ - listSecurityAdvisories(org, query = {}, options) { - return this._client.get(path`/orgs/${org}/security-advisories`, { query, ...options }); - } - /** - * Enables an authenticated GitHub App to find the organization's installation - * information. - * - * You must use a - * [JWT](https://docs.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) - * to access this endpoint. - * - * @example - * ```ts - * const installation = await client.orgs.retrieveInstallation( - * 'org', - * ); - * ``` - */ - retrieveInstallation(org, options) { - return this._client.get(path`/orgs/${org}/installation`, options); + const headers = buildHeaders([rawHeaders]); + if ( + // Pass raw type verbatim + ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && // Preserve legacy string encoding behavior for now + headers.values.has("content-type") || // `Blob` is superset of `File` + globalThis.Blob && body instanceof globalThis.Blob || // `FormData` -> `multipart/form-data` + body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded` + body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`) + globalThis.ReadableStream && body instanceof globalThis.ReadableStream + ) { + return { bodyHeaders: void 0, body }; + } else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) { + return { bodyHeaders: void 0, body: ReadableStreamFrom(body) }; + } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") { + return { + bodyHeaders: { "content-type": "application/x-www-form-urlencoded" }, + body: this.stringifyQuery(body) + }; + } else { + return __classPrivateFieldGet(this, _Stainless_encoder, "f").call(this, { body, headers }); } } - BaseOrgs3._key = Object.freeze(["orgs"]); - return BaseOrgs3; -})(); +}; +_a = Stainless, _Stainless_encoder = /* @__PURE__ */ new WeakMap(), _Stainless_instances = /* @__PURE__ */ new WeakSet(), _Stainless_baseURLOverridden = function _Stainless_baseURLOverridden2() { + return this.baseURL !== environments[this._options.environment || "production"]; +}; +Stainless.Stainless = _a; +Stainless.DEFAULT_TIMEOUT = 6e4; +Stainless.StainlessError = StainlessError; +Stainless.APIError = APIError; +Stainless.APIConnectionError = APIConnectionError; +Stainless.APIConnectionTimeoutError = APIConnectionTimeoutError; +Stainless.APIUserAbortError = APIUserAbortError; +Stainless.NotFoundError = NotFoundError; +Stainless.ConflictError = ConflictError; +Stainless.RateLimitError = RateLimitError; +Stainless.BadRequestError = BadRequestError; +Stainless.AuthenticationError = AuthenticationError; +Stainless.InternalServerError = InternalServerError; +Stainless.PermissionDeniedError = PermissionDeniedError; +Stainless.UnprocessableEntityError = UnprocessableEntityError; +Stainless.toFile = toFile; +Stainless.unwrapFile = unwrapFile; +Stainless.Projects = Projects; +Stainless.Builds = Builds; +Stainless.Orgs = Orgs; +Stainless.User = User; -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/resources/search.mjs -var BaseSearch = /* @__PURE__ */ (() => { - class BaseSearch6 extends APIResource { - /** - * Searches for query terms inside of a file. This method returns up to 100 results - * [per page](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api). - * - * When searching for code, you can get text match metadata for the file - * **content** and file **path** fields when you pass the `text-match` media type. - * For more details about how to receive highlighted search results, see - * [Text match metadata](https://docs.github.com/rest/search/search#text-match-metadata). - * - * For example, if you want to find the definition of the `addClass` function - * inside [jQuery](https://github.com/jquery/jquery) repository, your query would - * look something like this: - * - * `q=addClass+in:file+language:js+repo:jquery/jquery` - * - * This query searches for the keyword `addClass` within a file's contents. The - * query limits the search to files where the language is JavaScript in the - * `jquery/jquery` repository. - * - * Considerations for code search: - * - * Due to the complexity of searching code, there are a few restrictions on how - * searches are performed: - * - * - Only the _default branch_ is considered. In most cases, this will be the - * `master` branch. - * - Only files smaller than 384 KB are searchable. - * - You must always include at least one search term when searching source code. - * For example, searching for - * [`language:go`](https://github.com/search?utf8=%E2%9C%93&q=language%3Ago&type=Code) - * is not valid, while - * [`amazing language:go`](https://github.com/search?utf8=%E2%9C%93&q=amazing+language%3Ago&type=Code) - * is. - * - * This endpoint requires you to authenticate and limits you to 10 requests per - * minute. - */ - codeSearch(query, options) { - return this._client.get("/search/code", { query, ...options }); - } - /** - * Find commits via various criteria on the default branch (usually `main`). This - * method returns up to 100 results - * [per page](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api). - * - * When searching for commits, you can get text match metadata for the **message** - * field when you provide the `text-match` media type. For more details about how - * to receive highlighted search results, see - * [Text match metadata](https://docs.github.com/rest/search/search#text-match-metadata). - * - * For example, if you want to find commits related to CSS in the - * [octocat/Spoon-Knife](https://github.com/octocat/Spoon-Knife) repository. Your - * query would look something like this: - * - * `q=repo:octocat/Spoon-Knife+css` - */ - commitSearch(query, options) { - return this._client.get("/search/commits", { query, ...options }); - } - /** - * > [!WARNING] > **Notice:** Search for issues and pull requests will be - * > overridden by advanced search on November 4, 2025. You can read more about - * > this change on - * > [the GitHub blog](https://github.blog/changelog/2025-03-06-github-issues-projects-api-support-for-issues-advanced-search-and-more/). - * - * @deprecated - */ - issueSearch(query, options) { - return this._client.get("/search/issues", { query, ...options }); - } - /** - * Find labels in a repository with names or descriptions that match search - * keywords. Returns up to 100 results - * [per page](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api). - * - * When searching for labels, you can get text match metadata for the label - * **name** and **description** fields when you pass the `text-match` media type. - * For more details about how to receive highlighted search results, see - * [Text match metadata](https://docs.github.com/rest/search/search#text-match-metadata). - * - * For example, if you want to find labels in the `linguist` repository that match - * `bug`, `defect`, or `enhancement`. Your query might look like this: - * - * `q=bug+defect+enhancement&repository_id=64778136` - * - * The labels that best match the query appear first in the search results. - */ - labelSearch(query, options) { - return this._client.get("/search/labels", { query, ...options }); - } - /** - * Find repositories via various criteria. This method returns up to 100 results - * [per page](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api). - * - * When searching for repositories, you can get text match metadata for the - * **name** and **description** fields when you pass the `text-match` media type. - * For more details about how to receive highlighted search results, see - * [Text match metadata](https://docs.github.com/rest/search/search#text-match-metadata). - * - * For example, if you want to search for popular Tetris repositories written in - * assembly code, your query might look like this: - * - * `q=tetris+language:assembly&sort=stars&order=desc` - * - * This query searches for repositories with the word `tetris` in the name, the - * description, or the README. The results are limited to repositories where the - * primary language is assembly. The results are sorted by stars in descending - * order, so that the most popular repositories appear first in the search results. - */ - repositorySearch(query, options) { - return this._client.get("/search/repositories", { query, ...options }); - } - /** - * Find topics via various criteria. Results are sorted by best match. This method - * returns up to 100 results - * [per page](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api). - * See "[Searching topics](https://docs.github.com/articles/searching-topics/)" for - * a detailed list of qualifiers. - * - * When searching for topics, you can get text match metadata for the topic's - * **short_description**, **description**, **name**, or **display_name** field when - * you pass the `text-match` media type. For more details about how to receive - * highlighted search results, see - * [Text match metadata](https://docs.github.com/rest/search/search#text-match-metadata). - * - * For example, if you want to search for topics related to Ruby that are featured - * on https://github.com/topics. Your query might look like this: - * - * `q=ruby+is:featured` - * - * This query searches for topics with the keyword `ruby` and limits the results to - * find only topics that are featured. The topics that are the best match for the - * query appear first in the search results. - */ - topicSearch(query, options) { - return this._client.get("/search/topics", { query, ...options }); - } - /** - * Find users via various criteria. This method returns up to 100 results - * [per page](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api). - * - * When searching for users, you can get text match metadata for the issue - * **login**, public **email**, and **name** fields when you pass the `text-match` - * media type. For more details about highlighting search results, see - * [Text match metadata](https://docs.github.com/rest/search/search#text-match-metadata). - * For more details about how to receive highlighted search results, see - * [Text match metadata](https://docs.github.com/rest/search/search#text-match-metadata). - * - * For example, if you're looking for a list of popular users, you might try this - * query: - * - * `q=tom+repos:%3E42+followers:%3E1000` - * - * This query searches for users with the name `tom`. The results are restricted to - * users with more than 42 repositories and over 1,000 followers. - * - * This endpoint does not accept authentication and will only include publicly - * visible users. As an alternative, you can use the GraphQL API. The GraphQL API - * requires authentication and will return private users, including Enterprise - * Managed Users (EMUs), that you are authorized to view. For more information, see - * "[GraphQL Queries](https://docs.github.com/graphql/reference/queries#search)." - */ - userSearch(query, options) { - return this._client.get("/search/users", { query, ...options }); - } +// src/error.ts +var ActionError = class extends Error { + constructor(message, options) { + super(message, options); + this.name = "ActionError"; } - BaseSearch6._key = Object.freeze(["search"]); - return BaseSearch6; -})(); -var Search = class extends BaseSearch { }; +function maybeToActionError(error) { + if (error instanceof Stainless.BadRequestError || error instanceof Stainless.AuthenticationError || error instanceof Stainless.PermissionDeniedError || error instanceof Stainless.NotFoundError || error instanceof Stainless.UnprocessableEntityError) { + return new ActionError(error.message, { cause: error }); + } + return error; +} -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/lib/secrets.mjs -var import_libsodium_wrappers = __toESM(require_libsodium_wrappers(), 1); - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/resources/repos/repos.mjs -var BaseRepos3 = /* @__PURE__ */ (() => { - class BaseRepos6 extends APIResource { - constructor() { - super(...arguments); - this._client_search = new Search(this._client); - this.search = { - codeSearch: (params, options) => { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params; - query.q = `repo:${owner}/${repo} ${query.q}`; - return this._client_search.codeSearch(query, options); - }, - commitSearch: (params, options) => { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params; - query.q = `repo:${owner}/${repo} ${query.q}`; - return this._client_search.commitSearch(query, options); - }, - issueSearch: (params, options) => { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params; - query.q = `repo:${owner}/${repo} ${query.q}`; - return this._client_search.issueSearch(query, options); - }, - labelSearch: (params, options) => { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params; - query.q = `repo:${owner}/${repo} ${query.q}`; - return this._client_search.labelSearch(query, options); - } - }; - } - /** - * Creates a new repository for the authenticated user. - * - * OAuth app tokens and personal access tokens (classic) need the `public_repo` or - * `repo` scope to create a public repository, and `repo` scope to create a private - * repository. - * - * @example - * ```ts - * const fullRepository = await client.repos.create({ - * name: 'Hello-World', - * description: 'This is your first repo!', - * homepage: 'https://github.com', - * is_template: true, - * }); - * ``` - */ - create(body, options) { - return this._client.post("/user/repos", { body, ...options }); +// src/logger.ts +var LOG_LEVELS = { + debug: 0, + info: 1, + warn: 2, + error: 3, + off: 4 +}; +var COLORS2 = { + reset: "\x1B[0m", + bold: "\x1B[1m", + dim: "\x1B[90m", + cyan: "\x1B[36m", + green: "\x1B[32m", + yellow: "\x1B[33m", + red: "\x1B[31m", + magenta: "\x1B[35m" +}; +var LEVEL_COLORS = { + debug: COLORS2.cyan, + info: COLORS2.green, + warn: COLORS2.yellow, + error: COLORS2.red +}; +var LEVEL_LABELS = { + debug: "DEBUG", + info: "INFO", + warn: "WARN", + error: "ERROR" +}; +var LABEL_WIDTH = 5; +var LOG_LEVEL_CHOICES = ["debug", "info", "warn", "error", "off"]; +function formatTimestamp() { + const now = /* @__PURE__ */ new Date(); + const pad = (n, len = 2) => n.toString().padStart(len, "0"); + return `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}.${pad(now.getMilliseconds(), 3)}`; +} +function formatArgs(args) { + if (args.length === 0) return ""; + return args.map((arg) => { + if (arg === null) return "null"; + if (arg === void 0) return "undefined"; + if (typeof arg === "string") return arg; + if (arg instanceof Error) return arg.stack || arg.message; + try { + return JSON.stringify(arg, null, 2); + } catch { + return String(arg); } - /** - * The `parent` and `source` objects are present when the repository is a fork. - * `parent` is the repository this repository was forked from, `source` is the - * ultimate source for the network. - * - * > [!NOTE] - * > - * > - In order to see the `security_and_analysis` block for a repository you must - * > have admin permissions for the repository or be an owner or security manager - * > for the organization that owns the repository. For more information, see - * > "[Managing security managers in your organization](https://docs.github.com/organizations/managing-peoples-access-to-your-organization-with-roles/managing-security-managers-in-your-organization)." - * > - To view merge-related settings, you must have the `contents:read` and - * > `contents:write` permissions. - * - * @example - * ```ts - * const fullRepository = await client.repos.retrieve({ - * owner: 'owner', - * repo: 'repo', - * }); - * ``` - */ - retrieve(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}`, options); + }).join(" "); +} +function createLogFn(level, { context, minLevel, provider }) { + if (LOG_LEVELS[level] < minLevel) { + return () => { + }; + } + return (message, ...args) => { + const extra = formatArgs(args); + const line = [ + `${COLORS2.dim}${formatTimestamp()}${COLORS2.reset}`, + `${LEVEL_COLORS[level]}${COLORS2.bold}${LEVEL_LABELS[level].padEnd(LABEL_WIDTH)}${COLORS2.reset}`, + context ? `${COLORS2.magenta}[${context}]${COLORS2.reset}` : null, + message, + extra || null + ].filter(Boolean).join(" "); + const stream = level === "error" || level === "warn" ? process.stderr : process.stdout; + stream.write(line + "\n"); + if (level === "error") { + provider.emitErrorAnnotation(message + (extra ? " " + extra : "")); } - /** - * **Note**: To edit a repository's topics, use the - * [Replace all repository topics](https://docs.github.com/rest/repos/repos#replace-all-repository-topics) - * endpoint. - * - * @example - * ```ts - * const fullRepository = await client.repos.update({ - * owner: 'owner', - * repo: 'repo', - * description: 'This is your first repository', - * has_issues: true, - * has_projects: true, - * has_wiki: true, - * homepage: 'https://github.com', - * name: 'Hello-World', - * private: true, - * }); - * ``` - */ - update(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...body } = params ?? {}; - return this._client.patch(path`/repos/${owner}/${repo}`, { body, ...options }); + }; +} +var BUG_REPORT_URL = "https://github.com/stainless-api/upload-openapi-spec-action/issues"; +function createLoggerImpl(logContext) { + const { provider } = logContext; + const errorFn = createLogFn("error", logContext); + const groupStack = []; + return { + debug: createLogFn("debug", logContext), + info: createLogFn("info", logContext), + warn: createLogFn("warn", logContext), + error: errorFn, + fatal(message, ...args) { + errorFn(message, ...args); + const isActionError = args.some((arg) => arg instanceof ActionError); + if (!isActionError) { + process.stderr.write( + ` +This is a bug. Please report it at ${BUG_REPORT_URL} +` + ); + } + }, + child(childContext) { + const { context, ...rest } = logContext; + const newContext = context ? `${context}:${childContext}` : childContext; + return createLoggerImpl({ context: newContext, ...rest }); + }, + group(name) { + const id = provider.startGroup(name); + groupStack.push(id); + }, + groupEnd() { + const id = groupStack.pop(); + if (id !== void 0) { + provider.endGroup(id); + } + }, + withGroup(name, fn) { + const id = provider.startGroup(name); + try { + const result = fn(); + if (result instanceof Promise) { + return result.finally(() => provider.endGroup(id)); + } + provider.endGroup(id); + return result; + } catch (e) { + provider.endGroup(id); + throw e; + } } - /** - * Deleting a repository requires admin access. - * - * If an organization owner has configured the organization to prevent members from - * deleting organization-owned repositories, you will get a `403 Forbidden` - * response. - * - * OAuth app tokens and personal access tokens (classic) need the `delete_repo` - * scope to use this endpoint. - * - * @example - * ```ts - * await client.repos.delete({ owner: 'owner', repo: 'repo' }); - * ``` - */ - delete(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; - return this._client.delete(path`/repos/${owner}/${repo}`, { - ...options, - headers: buildHeaders([{ Accept: "*/*" }, options?.headers]) - }); + }; +} +function createLogger(options = {}) { + const minLevel = LOG_LEVELS[options.level ?? getInput("log_level", { choices: LOG_LEVEL_CHOICES }) ?? "info"]; + const provider = logging(); + return createLoggerImpl({ minLevel, provider }); +} +var logger = createLogger(); + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/errors.mjs +function isAbortError2(err) { + return typeof err === "object" && err !== null && // Spec-compliant fetch implementations + ("name" in err && err.name === "AbortError" || // Expo fetch + "message" in err && String(err.message).includes("FetchRequestCanceledException")); +} +var castToError2 = (err) => { + if (err instanceof Error) + return err; + if (typeof err === "object" && err !== null) { + try { + if (Object.prototype.toString.call(err) === "[object Error]") { + const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); + if (err.stack) + error.stack = err.stack; + if (err.cause && !error.cause) + error.cause = err.cause; + if (err.name) + error.name = err.name; + return error; + } + } catch { } - /** - * Whether the authenticated user has starred the repository. - * - * @example - * ```ts - * await client.repos.checkStarred({ - * owner: 'owner', - * repo: 'repo', - * }); - * ``` - */ - checkStarred(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; - return this._client.get(path`/user/starred/${owner}/${repo}`, { - ...options, - headers: buildHeaders([{ Accept: "*/*" }, options?.headers]) - }); + try { + return new Error(JSON.stringify(err)); + } catch { } - /** - * Compares two commits against one another. You can compare refs (branches or - * tags) and commit SHAs in the same repository, or you can compare refs and commit - * SHAs that exist in different repositories within the same repository network, - * including fork branches. For more information about how to view a repository's - * network, see - * "[Understanding connections between repositories](https://docs.github.com/repositories/viewing-activity-and-data-for-your-repository/understanding-connections-between-repositories)." - * - * This endpoint is equivalent to running the `git log BASE..HEAD` command, but it - * returns commits in a different order. The `git log BASE..HEAD` command returns - * commits in reverse chronological order, whereas the API returns commits in - * chronological order. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.diff`**: Returns the diff of the commit. - * - **`application/vnd.github.patch`**: Returns the patch of the commit. Diffs - * with binary data will have no `patch` property. - * - * The API response includes details about the files that were changed between the - * two commits. This includes the status of the change (if a file was added, - * removed, modified, or renamed), and details of the change itself. For example, - * files with a `renamed` status have a `previous_filename` field showing the - * previous filename of the file, and files with a `modified` status have a `patch` - * field showing the changes made to the file. - * - * When calling this endpoint without any paging parameter (`per_page` or `page`), - * the returned list is limited to 250 commits, and the last commit in the list is - * the most recent of the entire comparison. - * - * **Working with large comparisons** - * - * To process a response with a large number of commits, use a query parameter - * (`per_page` or `page`) to paginate the results. When using pagination: - * - * - The list of changed files is only shown on the first page of results, and it - * includes up to 300 changed files for the entire comparison. - * - The results are returned in chronological order, but the last commit in the - * returned list may not be the most recent one in the entire set if there are - * more pages of results. - * - * For more information on working with pagination, see - * "[Using pagination in the REST API](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api)." - * - * **Signature verification object** - * - * The response will include a `verification` object that describes the result of - * verifying the commit's signature. The `verification` object includes the - * following fields: - * - * | Name | Type | Description | - * | ------------- | --------- | ------------------------------------------------------------------------------------------------ | - * | `verified` | `boolean` | Indicates whether GitHub considers the signature in this commit to be verified. | - * | `reason` | `string` | The reason for verified value. Possible values and their meanings are enumerated in table below. | - * | `signature` | `string` | The signature that was extracted from the commit. | - * | `payload` | `string` | The value that was signed. | - * | `verified_at` | `string` | The date the signature was verified by GitHub. | - * - * These are the possible values for `reason` in the `verification` object: - * - * | Value | Description | - * | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------- | - * | `expired_key` | The key that made the signature is expired. | - * | `not_signing_key` | The "signing" flag is not among the usage flags in the GPG key that made the signature. | - * | `gpgverify_error` | There was an error communicating with the signature verification service. | - * | `gpgverify_unavailable` | The signature verification service is currently unavailable. | - * | `unsigned` | The object does not include a signature. | - * | `unknown_signature_type` | A non-PGP signature was found in the commit. | - * | `no_user` | No user was associated with the `committer` email address in the commit. | - * | `unverified_email` | The `committer` email address in the commit was associated with a user, but the email address is not verified on their account. | - * | `bad_email` | The `committer` email address in the commit is not included in the identities of the PGP key that made the signature. | - * | `unknown_key` | The key that made the signature has not been registered with any user's account. | - * | `malformed_signature` | There was an error parsing the signature. | - * | `invalid` | The signature could not be cryptographically verified using the key whose key-id was found in the signature. | - * | `valid` | None of the above errors applied, so the signature is considered to be verified. | - * - * @example - * ```ts - * const response = await client.repos.compareCommits( - * 'basehead', - * { owner: 'owner', repo: 'repo' }, - * ); - * ``` - */ - compareCommits(basehead, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/compare/${basehead}`, { query, ...options }); + } + return new Error(err); +}; + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/core/error.mjs +var GitHubError = /* @__PURE__ */ (() => { + class GitHubError2 extends Error { + } + return GitHubError2; +})(); +var APIError2 = class _APIError extends GitHubError { + constructor(status, error, message, headers) { + super(`${_APIError.makeMessage(status, error, message)}`); + this.status = status; + this.headers = headers; + this.error = error; + } + static makeMessage(status, error, message) { + const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message; + if (status && msg) { + return `${status} ${msg}`; } - /** - * Users with push access in a repository can create commit statuses for a given - * SHA. - * - * Note: there is a limit of 1000 statuses per `sha` and `context` within a - * repository. Attempts to create more than 1000 statuses will result in a - * validation error. - * - * @example - * ```ts - * const response = await client.repos.createCommitStatus( - * 'sha', - * { - * owner: 'owner', - * repo: 'repo', - * state: 'success', - * context: 'continuous-integration/jenkins', - * description: 'The build succeeded!', - * target_url: 'https://example.com/build/status', - * }, - * ); - * ``` - */ - createCommitStatus(sha, params, options) { - const { owner = this._client.owner, repo = this._client.repo, ...body } = params; - return this._client.post(path`/repos/${owner}/${repo}/statuses/${sha}`, { body, ...options }); + if (status) { + return `${status} status code (no body)`; } - /** - * You can use this endpoint to trigger a webhook event called - * `repository_dispatch` when you want activity that happens outside of GitHub to - * trigger a GitHub Actions workflow or GitHub App webhook. You must configure your - * GitHub Actions workflow or GitHub App to run when the `repository_dispatch` - * event occurs. For an example `repository_dispatch` webhook payload, see - * "[RepositoryDispatchEvent](https://docs.github.com/webhooks/event-payloads/#repository_dispatch)." - * - * The `client_payload` parameter is available for any extra information that your - * workflow might need. This parameter is a JSON payload that will be passed on - * when the webhook event is dispatched. For example, the `client_payload` can - * include a message that a user would like to send using a GitHub Actions - * workflow. Or the `client_payload` can be used as a test to debug your workflow. - * - * This input example shows how you can use the `client_payload` as a test to debug - * your workflow. - * - * OAuth app tokens and personal access tokens (classic) need the `repo` scope to - * use this endpoint. - * - * @example - * ```ts - * await client.repos.createDispatchEvent({ - * owner: 'owner', - * repo: 'repo', - * event_type: 'on-demand-test', - * client_payload: { unit: false, integration: true }, - * }); - * ``` - */ - createDispatchEvent(params, options) { - const { owner = this._client.owner, repo = this._client.repo, ...body } = params; - return this._client.post(path`/repos/${owner}/${repo}/dispatches`, { - body, - ...options, - headers: buildHeaders([{ Accept: "*/*" }, options?.headers]) - }); + if (msg) { + return msg; } - /** - * Creates a new repository in the specified organization. The authenticated user - * must be a member of the organization. - * - * OAuth app tokens and personal access tokens (classic) need the `public_repo` or - * `repo` scope to create a public repository, and `repo` scope to create a private - * repository. - * - * @example - * ```ts - * const fullRepository = await client.repos.createForOrg( - * 'org', - * { - * name: 'Hello-World', - * description: 'This is your first repository', - * has_issues: true, - * has_projects: true, - * has_wiki: true, - * homepage: 'https://github.com', - * }, - * ); - * ``` - */ - createForOrg(org, body, options) { - return this._client.post(path`/orgs/${org}/repos`, { body, ...options }); + return "(no status code or body)"; + } + static generate(status, errorResponse, message, headers) { + if (!status || !headers) { + return new APIConnectionError2({ message, cause: castToError2(errorResponse) }); } - /** - * Creates a new repository using a repository template. Use the `template_owner` - * and `template_repo` route parameters to specify the repository to use as the - * template. If the repository is not public, the authenticated user must own or be - * a member of an organization that owns the repository. To check if a repository - * is available to use as a template, get the repository's information using the - * [Get a repository](https://docs.github.com/rest/repos/repos#get-a-repository) - * endpoint and check that the `is_template` key is `true`. - * - * OAuth app tokens and personal access tokens (classic) need the `public_repo` or - * `repo` scope to create a public repository, and `repo` scope to create a private - * repository. - * - * @example - * ```ts - * const fullRepository = - * await client.repos.createFromTemplate('template_repo', { - * template_owner: 'template_owner', - * name: 'Hello-World', - * description: 'This is your first repository', - * owner: 'octocat', - * }); - * ``` - */ - createFromTemplate(templateRepo, params, options) { - const { template_owner, ...body } = params; - return this._client.post(path`/repos/${template_owner}/${templateRepo}/generate`, { body, ...options }); + const error = errorResponse; + if (status === 400) { + return new BadRequestError2(status, error, message, headers); } - /** - * Gets a redirect URL to download a tar archive for a repository. If you omit - * `:ref`, the repository’s default branch (usually `main`) will be used. Please - * make sure your HTTP framework is configured to follow redirects or you will need - * to use the `Location` header to make a second `GET` request. - * - * > [!NOTE] For private repositories, these links are temporary and expire after - * > five minutes. - * - * @example - * ```ts - * await client.repos.downloadTarball('ref', { - * owner: 'owner', - * repo: 'repo', - * }); - * ``` - */ - downloadTarball(ref, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/tarball/${ref}`, { - ...options, - headers: buildHeaders([{ Accept: "*/*" }, options?.headers]) - }); + if (status === 401) { + return new AuthenticationError2(status, error, message, headers); } - /** - * Gets a redirect URL to download a zip archive for a repository. If you omit - * `:ref`, the repository’s default branch (usually `main`) will be used. Please - * make sure your HTTP framework is configured to follow redirects or you will need - * to use the `Location` header to make a second `GET` request. - * - * > [!NOTE] For private repositories, these links are temporary and expire after - * > five minutes. If the repository is empty, you will receive a 404 when you - * > follow the redirect. - * - * @example - * ```ts - * await client.repos.downloadZipball('ref', { - * owner: 'owner', - * repo: 'repo', - * }); - * ``` - */ - downloadZipball(ref, params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/zipball/${ref}`, { - ...options, - headers: buildHeaders([{ Accept: "*/*" }, options?.headers]) - }); - } - /** - * Enables an authenticated GitHub App to find the repository's installation - * information. The installation's account type will be either an organization or a - * user account, depending which account the repository belongs to. - * - * You must use a - * [JWT](https://docs.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) - * to access this endpoint. - * - * @example - * ```ts - * const installation = await client.repos.getInstallationInfo( - * { owner: 'owner', repo: 'repo' }, - * ); - * ``` - */ - getInstallationInfo(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/installation`, options); - } - /** - * This method returns the contents of the repository's license file, if one is - * detected. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.raw+json`**: Returns the raw contents of the - * license. - * - **`application/vnd.github.html+json`**: Returns the license contents in HTML. - * Markup languages are rendered to HTML using GitHub's open-source - * [Markup library](https://github.com/github/markup). - * - * @example - * ```ts - * const response = await client.repos.getLicense({ - * owner: 'owner', - * repo: 'repo', - * }); - * ``` - */ - getLicense(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/license`, { query, ...options }); - } - /** - * Get the code security configuration that manages a repository's code security - * settings. - * - * The authenticated user must be an administrator or security manager for the - * organization to use this endpoint. - * - * OAuth app tokens and personal access tokens (classic) need the `repo` scope to - * use this endpoint. - * - * @example - * ```ts - * const response = - * await client.repos.getSecurityConfiguration({ - * owner: 'owner', - * repo: 'repo', - * }); - * ``` - */ - getSecurityConfiguration(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/code-security-configuration`, options); + if (status === 403) { + return new PermissionDeniedError2(status, error, message, headers); } - /** - * Lists a detailed history of changes to a repository, such as pushes, merges, - * force pushes, and branch changes, and associates these changes with commits and - * users. - * - * For more information about viewing repository activity, see - * "[Viewing activity and data for your repository](https://docs.github.com/repositories/viewing-activity-and-data-for-your-repository)." - * - * @example - * ```ts - * const response = await client.repos.listActivity({ - * owner: 'owner', - * repo: 'repo', - * }); - * ``` - */ - listActivity(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/activity`, { query, ...options }); + if (status === 404) { + return new NotFoundError2(status, error, message, headers); } - /** - * > [!NOTE] This API is not built to serve real-time use cases. Depending on the - * > time of day, event latency can be anywhere from 30s to 6h. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const repoListEventsResponse of client.repos.listEvents( - * { owner: 'owner', repo: 'repo' }, - * )) { - * // ... - * } - * ``` - */ - listEvents(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.getAPIList(path`/repos/${owner}/${repo}/events`, NumberedPage, { query, ...options }); + if (status === 409) { + return new ConflictError2(status, error, message, headers); } - /** - * Lists repositories that the authenticated user has explicit permission (`:read`, - * `:write`, or `:admin`) to access. - * - * The authenticated user has explicit permission to access repositories they own, - * repositories where they are a collaborator, and repositories that they can - * access through an organization membership. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const repository of client.repos.listForCurrentUser()) { - * // ... - * } - * ``` - */ - listForCurrentUser(query = {}, options) { - return this._client.getAPIList("/user/repos", NumberedPage, { query, ...options }); + if (status === 422) { + return new UnprocessableEntityError2(status, error, message, headers); } - /** - * Lists repositories for the specified organization. - * - * > [!NOTE] In order to see the `security_and_analysis` block for a repository you - * > must have admin permissions for the repository or be an owner or security - * > manager for the organization that owns the repository. For more information, - * > see - * > "[Managing security managers in your organization](https://docs.github.com/organizations/managing-peoples-access-to-your-organization-with-roles/managing-security-managers-in-your-organization)." - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const minimalRepository of client.repos.listForOrg( - * 'org', - * )) { - * // ... - * } - * ``` - */ - listForOrg(org, query = {}, options) { - return this._client.getAPIList(path`/orgs/${org}/repos`, NumberedPage, { - query, - ...options - }); + if (status === 429) { + return new RateLimitError2(status, error, message, headers); } - /** - * Lists public repositories for the specified user. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const minimalRepository of client.repos.listForUser( - * 'username', - * )) { - * // ... - * } - * ``` - */ - listForUser(username, query = {}, options) { - return this._client.getAPIList(path`/users/${username}/repos`, NumberedPage, { - query, - ...options - }); + if (status >= 500) { + return new InternalServerError2(status, error, message, headers); } - /** - * Lists all public repositories in the order that they were created. - * - * Note: - * - * - For GitHub Enterprise Server, this endpoint will only list repositories - * available to all users on the enterprise. - * - Pagination is powered exclusively by the `since` parameter. Use the - * [Link header](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api#using-link-headers) - * to get the URL for the next page of repositories. - * - * @example - * ```ts - * const minimalRepositories = await client.repos.listPublic(); - * ``` - */ - listPublic(query = {}, options) { - return this._client.get("/repositories", { query, ...options }); - } - /** - * Lists the people that have starred the repository. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.star+json`**: Includes a timestamp of when the star - * was created. - * - * @example - * ```ts - * const response = await client.repos.listStargazers({ - * owner: 'owner', - * repo: 'repo', - * }); - * ``` - */ - listStargazers(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.get(path`/repos/${owner}/${repo}/stargazers`, { query, ...options }); - } - /** - * Lists repositories the authenticated user has starred. - * - * This endpoint supports the following custom media types. For more information, - * see - * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." - * - * - **`application/vnd.github.star+json`**: Includes a timestamp of when the star - * was created. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const repository of client.repos.listStarred()) { - * // ... - * } - * ``` - */ - listStarred(query = {}, options) { - return this._client.getAPIList("/user/starred", NumberedPage, { query, ...options }); - } - /** - * Lists the people watching the specified repository. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const simpleUser of client.repos.listWatchers({ - * owner: 'owner', - * repo: 'repo', - * })) { - * // ... - * } - * ``` - */ - listWatchers(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; - return this._client.getAPIList(path`/repos/${owner}/${repo}/subscribers`, NumberedPage, { query, ...options }); - } - /** - * Merge a branch - * - * @example - * ```ts - * const commit = await client.repos.mergeBranch({ - * owner: 'owner', - * repo: 'repo', - * base: 'master', - * head: 'cool_feature', - * commit_message: 'Shipped cool_feature!', - * }); - * ``` - */ - mergeBranch(params, options) { - const { owner = this._client.owner, repo = this._client.repo, ...body } = params; - return this._client.post(path`/repos/${owner}/${repo}/merges`, { body, ...options }); - } - /** - * Note that you'll need to set `Content-Length` to zero when calling out to this - * endpoint. For more information, see - * "[HTTP method](https://docs.github.com/rest/guides/getting-started-with-the-rest-api#http-method)." - * - * @example - * ```ts - * await client.repos.star({ owner: 'owner', repo: 'repo' }); - * ``` - */ - star(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; - return this._client.put(path`/user/starred/${owner}/${repo}`, { - ...options, - headers: buildHeaders([{ Accept: "*/*" }, options?.headers]) - }); - } - /** - * Sync a branch of a forked repository to keep it up-to-date with the upstream - * repository. - * - * @example - * ```ts - * const response = await client.repos.syncFork({ - * owner: 'owner', - * repo: 'repo', - * branch: 'main', - * }); - * ``` - */ - syncFork(params, options) { - const { owner = this._client.owner, repo = this._client.repo, ...body } = params; - return this._client.post(path`/repos/${owner}/${repo}/merge-upstream`, { body, ...options }); - } - /** - * A transfer request will need to be accepted by the new owner when transferring a - * personal repository to another user. The response will contain the original - * `owner`, and the transfer will continue asynchronously. For more details on the - * requirements to transfer personal and organization-owned repositories, see - * [about repository transfers](https://docs.github.com/articles/about-repository-transfers/). - * - * @example - * ```ts - * const minimalRepository = await client.repos.transfer({ - * owner: 'owner', - * repo: 'repo', - * new_owner: 'github', - * new_name: 'octorepo', - * team_ids: [12, 345], - * }); - * ``` - */ - transfer(params, options) { - const { owner = this._client.owner, repo = this._client.repo, ...body } = params; - return this._client.post(path`/repos/${owner}/${repo}/transfer`, { body, ...options }); - } - /** - * Unstar a repository that the authenticated user has previously starred. - * - * @example - * ```ts - * await client.repos.unstar({ owner: 'owner', repo: 'repo' }); - * ``` - */ - unstar(params = {}, options) { - const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; - return this._client.delete(path`/user/starred/${owner}/${repo}`, { - ...options, - headers: buildHeaders([{ Accept: "*/*" }, options?.headers]) - }); + return new _APIError(status, error, message, headers); + } +}; +var APIUserAbortError2 = class extends APIError2 { + constructor({ message } = {}) { + super(void 0, void 0, message || "Request was aborted.", void 0); + } +}; +var APIConnectionError2 = class extends APIError2 { + constructor({ message, cause }) { + super(void 0, void 0, message || "Connection error.", void 0); + if (cause) + this.cause = cause; + } +}; +var APIConnectionTimeoutError2 = class extends APIConnectionError2 { + constructor({ message } = {}) { + super({ message: message ?? "Request timed out." }); + } +}; +var BadRequestError2 = class extends APIError2 { +}; +var AuthenticationError2 = class extends APIError2 { +}; +var PermissionDeniedError2 = class extends APIError2 { +}; +var NotFoundError2 = class extends APIError2 { +}; +var ConflictError2 = class extends APIError2 { +}; +var UnprocessableEntityError2 = class extends APIError2 { +}; +var RateLimitError2 = class extends APIError2 { +}; +var InternalServerError2 = class extends APIError2 { +}; + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/core/resource.mjs +var APIResource2 = /* @__PURE__ */ (() => { + class APIResource4 { + constructor(client) { + this._client = client; } } - BaseRepos6._key = Object.freeze(["repos"]); - return BaseRepos6; + APIResource4._key = []; + return APIResource4; })(); -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/utils/env.mjs -var readEnv = (env) => { - if (typeof globalThis.process !== "undefined") { - return globalThis.process.env?.[env]?.trim() ?? void 0; - } - if (typeof globalThis.Deno !== "undefined") { - return globalThis.Deno.env?.get?.(env)?.trim(); - } - return void 0; -}; +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/tslib.mjs +function __classPrivateFieldSet2(receiver, state, value, kind, f) { + if (kind === "m") + throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; +} +function __classPrivateFieldGet2(receiver, state, kind, f) { + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/lib/auth.mjs -var import_jsonwebtoken = __toESM(require_jsonwebtoken(), 1); -async function getAuthToken({ authMethods, owner, repo, logger: logger2 }) { - const method = authMethods.find((method2) => method2.owner === owner) ?? authMethods.at(-1); - if (!method || method.owner !== owner && method.owner !== "*") { - throw new Error("No matching auth method found. Did you set a fallback auth method, with owner *?"); +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/utils/values.mjs +var startsWithSchemeRegexp2 = /^[a-z][a-z0-9+.-]*:/i; +var isAbsoluteURL2 = (url) => { + return startsWithSchemeRegexp2.test(url); +}; +var isArray2 = (val) => (isArray2 = Array.isArray, isArray2(val)); +var isReadonlyArray2 = isArray2; +function maybeObj2(x) { + if (typeof x !== "object") { + return {}; } - if ("token" in method) { - return { authToken: method.token, expires: method.expires }; + return x ?? {}; +} +function isEmptyObj2(obj) { + if (!obj) + return true; + for (const _k in obj) + return false; + return true; +} +function hasOwn2(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +var validatePositiveInteger2 = (name, n) => { + if (typeof n !== "number" || !Number.isInteger(n)) { + throw new GitHubError(`${name} must be an integer`); } - const appAuth = await getAppToken(method); - const client = createClient({ - owner, - repo, - authToken: appAuth.authToken, - resources: [BaseRepos3, BaseOrgs, BaseInstallations] - }); - let installationId = method.installationId; + if (n < 0) { + throw new GitHubError(`${name} must be a positive integer`); + } + return n; +}; +var safeJSON2 = (text) => { try { - if (!installationId) { - if (repo) { - const { id } = await client.repos.getInstallationInfo(); - installationId = id; - } else { - const { id } = await client.orgs.retrieveInstallation(owner); - installationId = id; - } - } - } catch (e) { - logger2?.warn(`No installation ID found for ${owner}/${repo}, using app token instead`, e); + return JSON.parse(text); + } catch (err) { + return void 0; } - if (!installationId) { - return appAuth; +}; + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/utils/log.mjs +var levelNumbers2 = { + off: 0, + error: 200, + warn: 300, + info: 400, + debug: 500 +}; +var parseLogLevel2 = (maybeLevel, sourceName, client) => { + if (!maybeLevel) { + return void 0; } - try { - const { token, expires_at } = await client.apps.installations.createAccessToken(installationId); - return { authToken: token, expires: new Date(expires_at) }; - } catch (e) { - logger2?.warn(`Failed to get installation token for ${installationId}, using app token instead`, e); + if (hasOwn2(levelNumbers2, maybeLevel)) { + return maybeLevel; } - return appAuth; -} -async function getAppToken(method) { - const iat = Math.floor(Date.now() / 1e3) - 30; - const exp = iat + 60 * 10; - const appToken = import_jsonwebtoken.default.sign({ iat, exp, iss: method.appId }, method.privateKey, { - algorithm: "RS256" - }); - const appTokenExpires = new Date(exp * 1e3); - return { authToken: appToken, expires: appTokenExpires }; + loggerFor2(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers2))}`); + return void 0; +}; +function noop2() { } - -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/client.mjs -var _BaseGitHub_instances; -var _BaseGitHub_encoder; -var _BaseGitHub_baseURLOverridden; -var BaseGitHub = /* @__PURE__ */ (() => { - class BaseGitHub3 { - /** - * API Client for interfacing with the GitHub API. - * - * @param {string | null | undefined} [opts.authToken=process.env['GITHUB_AUTH_TOKEN'] ?? null] - * @param {string | null | undefined} [opts.owner] - * @param {string | null | undefined} [opts.repo] - * @param {string | null | undefined} [opts.webhookSecret=process.env['GITHUB_WEBHOOK_SECRET'] ?? null] - * @param {string} [opts.baseURL=process.env['GITHUB_BASE_URL'] ?? https://api.github.com] - Override the default base URL for the API. - * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. - * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. - * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. - * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. - * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. - * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. - */ - constructor({ baseURL = readEnv("GITHUB_BASE_URL"), authToken = readEnv("GITHUB_AUTH_TOKEN") ?? null, owner = null, repo = null, webhookSecret = readEnv("GITHUB_WEBHOOK_SECRET") ?? null, ...opts } = {}) { - _BaseGitHub_instances.add(this); - _BaseGitHub_encoder.set(this, void 0); - const options = { - authToken, - owner, - repo, - webhookSecret, - ...opts, - baseURL: baseURL || `https://api.github.com` - }; - this.baseURL = options.baseURL; - this.timeout = options.timeout ?? BaseGitHub3.DEFAULT_TIMEOUT; - this.logger = options.logger ?? console; - const defaultLogLevel = "warn"; - this.logLevel = defaultLogLevel; - this.logLevel = parseLogLevel(options.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel(readEnv("GITHUB_LOG"), "process.env['GITHUB_LOG']", this) ?? defaultLogLevel; - this.fetchOptions = options.fetchOptions; - this.maxRetries = options.maxRetries ?? 2; - this.fetch = options.fetch ?? getDefaultFetch(); - __classPrivateFieldSet(this, _BaseGitHub_encoder, FallbackEncoder, "f"); - this._options = options; - this.authToken = authToken; - this.owner = owner; - this.repo = repo; - this.webhookSecret = webhookSecret; - } - /** - * Create a new client instance re-using the same options given to the current client with optional overriding. - */ - withOptions(options) { - const client = new this.constructor({ - ...this._options, - baseURL: this.baseURL, - maxRetries: this.maxRetries, - timeout: this.timeout, - logger: this.logger, - logLevel: this.logLevel, - fetch: this.fetch, - fetchOptions: this.fetchOptions, - authToken: this.authToken, - owner: this.owner, - repo: this.repo, - webhookSecret: this.webhookSecret, - ...options - }); - return client; - } - /** - * Get Hypermedia links to resources accessible in GitHub's REST API - */ - retrieve(options) { - return this.get("/", options); - } - /** - * Get a random sentence from the Zen of GitHub - */ - zen(options) { - return this.get("/zen", { - ...options, - headers: buildHeaders([{ Accept: "text/plain" }, options?.headers]) - }); +function makeLogFn2(fnLevel, logger2, logLevel) { + if (!logger2 || levelNumbers2[fnLevel] > levelNumbers2[logLevel]) { + return noop2; + } else { + return logger2[fnLevel].bind(logger2); + } +} +var noopLogger2 = { + error: noop2, + warn: noop2, + info: noop2, + debug: noop2 +}; +var cachedLoggers2 = /* @__PURE__ */ new WeakMap(); +function loggerFor2(client) { + const logger2 = client.logger; + const logLevel = client.logLevel ?? "off"; + if (!logger2) { + return noopLogger2; + } + const cachedLogger = cachedLoggers2.get(logger2); + if (cachedLogger && cachedLogger[0] === logLevel) { + return cachedLogger[1]; + } + const levelLogger = { + error: makeLogFn2("error", logger2, logLevel), + warn: makeLogFn2("warn", logger2, logLevel), + info: makeLogFn2("info", logger2, logLevel), + debug: makeLogFn2("debug", logger2, logLevel) + }; + cachedLoggers2.set(logger2, [logLevel, levelLogger]); + return levelLogger; +} +var formatRequestDetails2 = (details) => { + if (details.options) { + details.options = { ...details.options }; + delete details.options["headers"]; + } + if (details.headers) { + details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ + name, + name.toLowerCase() === "authorization" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value + ])); + } + if ("retryOfRequestLogID" in details) { + if (details.retryOfRequestLogID) { + details.retryOf = details.retryOfRequestLogID; } - defaultQuery() { - return this._options.defaultQuery; + delete details.retryOfRequestLogID; + } + return details; +}; + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/parse.mjs +async function defaultParseResponse2(client, props) { + const { response, requestLogID, retryOfRequestLogID, startTime } = props; + const body = await (async () => { + if (response.status === 204) { + return null; } - validateHeaders({ values, nulls }) { - return; + if (props.options.__binaryResponse) { + return response; } - async authHeaders(opts) { - if (this.authToken == null) { + const contentType = response.headers.get("content-type"); + const mediaType = contentType?.split(";")[0]?.trim(); + const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json"); + if (isJSON) { + const contentLength = response.headers.get("content-length"); + if (contentLength === "0") { return void 0; } - return buildHeaders([{ Authorization: `Bearer ${this.authToken}` }]); + const json = await response.json(); + return json; } - /** - * Given a list of available auth methods, get an auth token to access the - * given GitHub `owner` (and optionally `repo`), and set it on this client. - */ - async getAuthToken(opts) { - if (this.authToken != null) { - return this.authToken; - } - const owner = opts.owner ?? this.owner; - const repo = opts.repo ?? this.repo; - if (owner == null) { - throw new Error("Specify an owner to get a token for."); - } - const { authToken } = await getAuthToken({ - authMethods: opts.authMethods, - owner, - repo, - logger: this.logger + const text = await response.text(); + return text; + })(); + loggerFor2(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails2({ + retryOfRequestLogID, + url: response.url, + status: response.status, + body, + durationMs: Date.now() - startTime + })); + return body; +} + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/core/api-promise.mjs +var _APIPromise_client2; +var APIPromise2 = /* @__PURE__ */ (() => { + class APIPromise4 extends Promise { + constructor(client, responsePromise, parseResponse = defaultParseResponse2) { + super((resolve) => { + resolve(null); }); - this.authToken = authToken; - return authToken; - } - stringifyQuery(query) { - return stringify(query, { arrayFormat: "comma" }); - } - getUserAgent() { - return `${this.constructor.name}/JS ${VERSION}`; - } - defaultIdempotencyKey() { - return `stainless-node-retry-${uuid4()}`; - } - makeStatusError(status, error, message, headers) { - return APIError.generate(status, error, message, headers); + this.responsePromise = responsePromise; + this.parseResponse = parseResponse; + _APIPromise_client2.set(this, void 0); + __classPrivateFieldSet2(this, _APIPromise_client2, client, "f"); } - buildURL(path7, query, defaultBaseURL) { - const baseURL = !__classPrivateFieldGet(this, _BaseGitHub_instances, "m", _BaseGitHub_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL; - const url = isAbsoluteURL(path7) ? new URL(path7) : new URL(baseURL + (baseURL.endsWith("/") && path7.startsWith("/") ? path7.slice(1) : path7)); - const defaultQuery = this.defaultQuery(); - if (!isEmptyObj(defaultQuery)) { - query = { ...defaultQuery, ...query }; - } - if (typeof query === "object" && query && !Array.isArray(query)) { - url.search = this.stringifyQuery(query); - } - return url.toString(); + _thenUnwrap(transform) { + return new APIPromise4(__classPrivateFieldGet2(this, _APIPromise_client2, "f"), this.responsePromise, async (client, props) => transform(await this.parseResponse(client, props), props)); } /** - * Used as a callback for mutating the given `FinalRequestOptions` object. + * Gets the raw `Response` instance instead of parsing the response + * data. + * + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. */ - async prepareOptions(options) { + asResponse() { + return this.responsePromise.then((p) => p.response); } /** - * Used as a callback for mutating the given `RequestInit` object. + * Gets the parsed response data and the raw `Response` instance. * - * This is useful for cases where you want to add certain headers based off of - * the request properties, e.g. `method` or `url`. + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. */ - async prepareRequest(request, { url, options }) { - } - get(path7, opts) { - return this.methodRequest("get", path7, opts); + async withResponse() { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { data, response }; } - post(path7, opts) { - return this.methodRequest("post", path7, opts); + parse() { + if (!this.parsedPromise) { + this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet2(this, _APIPromise_client2, "f"), data)); + } + return this.parsedPromise; } - patch(path7, opts) { - return this.methodRequest("patch", path7, opts); + then(onfulfilled, onrejected) { + return this.parse().then(onfulfilled, onrejected); } - put(path7, opts) { - return this.methodRequest("put", path7, opts); + catch(onrejected) { + return this.parse().catch(onrejected); } - delete(path7, opts) { - return this.methodRequest("delete", path7, opts); + finally(onfinally) { + return this.parse().finally(onfinally); } - methodRequest(method, path7, opts) { - return this.request(Promise.resolve(opts).then((opts2) => { - return { method, path: path7, ...opts2 }; - })); + } + _APIPromise_client2 = /* @__PURE__ */ new WeakMap(); + return APIPromise4; +})(); + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/core/pagination.mjs +var _AbstractPage_client2; +var AbstractPage2 = /* @__PURE__ */ (() => { + class AbstractPage3 { + constructor(client, response, body, options) { + _AbstractPage_client2.set(this, void 0); + __classPrivateFieldSet2(this, _AbstractPage_client2, client, "f"); + this.options = options; + this.response = response; + this.body = body; } - request(options, remainingRetries = null) { - return new APIPromise(this, this.makeRequest(options, remainingRetries, void 0)); + hasNextPage() { + const items = this.getPaginatedItems(); + if (!items.length) + return false; + return this.nextPageRequestOptions() != null; } - async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { - const options = await optionsInput; - const maxRetries = options.maxRetries ?? this.maxRetries; - if (retriesRemaining == null) { - retriesRemaining = maxRetries; - } - await this.prepareOptions(options); - const { req, url, timeout } = await this.buildRequest(options, { - retryCount: maxRetries - retriesRemaining - }); - await this.prepareRequest(req, { url, options }); - const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0"); - const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`; - const startTime = Date.now(); - loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({ - retryOfRequestLogID, - method: options.method, - url, - options, - headers: req.headers - })); - if (options.signal?.aborted) { - throw new APIUserAbortError(); + async getNextPage() { + const nextOptions = this.nextPageRequestOptions(); + if (!nextOptions) { + throw new GitHubError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`."); } - const controller = new AbortController(); - const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError); - const headersTime = Date.now(); - if (response instanceof globalThis.Error) { - const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; - if (options.signal?.aborted) { - throw new APIUserAbortError(); - } - const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : "")); - if (retriesRemaining) { - loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`); - loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails({ - retryOfRequestLogID, - url, - durationMs: headersTime - startTime, - message: response.message - })); - return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); - } - loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`); - loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails({ - retryOfRequestLogID, - url, - durationMs: headersTime - startTime, - message: response.message - })); - if (isTimeout) { - throw new APIConnectionTimeoutError(); - } - throw new APIConnectionError({ cause: response }); + return await __classPrivateFieldGet2(this, _AbstractPage_client2, "f").requestAPIList(this.constructor, nextOptions); + } + async *iterPages() { + let page = this; + yield page; + while (page.hasNextPage()) { + page = await page.getNextPage(); + yield page; } - const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`; - if (!response.ok) { - const shouldRetry = await this.shouldRetry(response); - if (retriesRemaining && shouldRetry) { - const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`; - await CancelReadableStream(response.body); - loggerFor(this).info(`${responseInfo} - ${retryMessage2}`); - loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - durationMs: headersTime - startTime - })); - return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); + } + async *[(_AbstractPage_client2 = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() { + for await (const page of this.iterPages()) { + for (const item of page.getPaginatedItems()) { + yield item; } - const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; - loggerFor(this).info(`${responseInfo} - ${retryMessage}`); - const errText = await response.text().catch((err2) => castToError(err2).message); - const errJSON = safeJSON(errText); - const errMessage = errJSON ? void 0 : errText; - loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - message: errMessage, - durationMs: Date.now() - startTime - })); - const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); - throw err; } - loggerFor(this).info(responseInfo); - loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - durationMs: headersTime - startTime - })); - return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; - } - getAPIList(path7, Page2, opts) { - return this.requestAPIList(Page2, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path7, ...opts2 })) : { method: "get", path: path7, ...opts }); } - requestAPIList(Page2, options) { - const request = this.makeRequest(options, null, void 0); - return new PagePromise(this, request, Page2); + } + return AbstractPage3; +})(); +var PagePromise2 = /* @__PURE__ */ (() => { + class PagePromise3 extends APIPromise2 { + constructor(client, request, Page2) { + super(client, request, async (client2, props) => new Page2(client2, props.response, await defaultParseResponse2(client2, props), props.options)); } - async fetchWithTimeout(url, init, ms, controller) { - const { signal, method, ...options } = init || {}; - const abort = this._makeAbort(controller); - if (signal) - signal.addEventListener("abort", abort, { once: true }); - const timeout = setTimeout(abort, ms); - const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body; - const fetchOptions = { - signal: controller.signal, - ...isReadableBody ? { duplex: "half" } : {}, - method: "GET", - ...options - }; - if (method) { - fetchOptions.method = method.toUpperCase(); - } - try { - return await this.fetch.call(void 0, url, fetchOptions); - } finally { - clearTimeout(timeout); + /** + * Allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ + async *[Symbol.asyncIterator]() { + const page = await this; + for await (const item of page) { + yield item; } } - async shouldRetry(response) { - const shouldRetryHeader = response.headers.get("x-should-retry"); - if (shouldRetryHeader === "true") - return true; - if (shouldRetryHeader === "false") - return false; - if (response.status === 408) - return true; - if (response.status === 409) - return true; - if (response.status === 429) - return true; - if (response.status >= 500) - return true; - return false; - } - async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { - let timeoutMillis; - const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms"); - if (retryAfterMillisHeader) { - const timeoutMs = parseFloat(retryAfterMillisHeader); - if (!Number.isNaN(timeoutMs)) { - timeoutMillis = timeoutMs; - } - } - const retryAfterHeader = responseHeaders?.get("retry-after"); - if (retryAfterHeader && !timeoutMillis) { - const timeoutSeconds = parseFloat(retryAfterHeader); - if (!Number.isNaN(timeoutSeconds)) { - timeoutMillis = timeoutSeconds * 1e3; - } else { - timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); - } - } - if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1e3)) { - const maxRetries = options.maxRetries ?? this.maxRetries; - timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + } + return PagePromise3; +})(); +var NumberedPage = class extends AbstractPage2 { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body || []; + } + getPaginatedItems() { + return this.data ?? []; + } + nextPageRequestOptions() { + const query = this.options.query; + const currentPage = query?.page ?? 1; + return { + ...this.options, + query: { + ...maybeObj2(this.options.query), + page: currentPage + 1 } - await sleep(timeoutMillis); - return this.makeRequest(options, retriesRemaining - 1, requestLogID); + }; + } +}; + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/utils/path.mjs +function encodeURIPath2(str) { + return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); +} +var EMPTY2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); +var createPathTagFunction2 = (pathEncoder = encodeURIPath2) => function path7(statics, ...params) { + if (statics.length === 1) + return statics[0]; + let postPath = false; + const invalidSegments = []; + const path8 = statics.reduce((previousValue, currentValue, index) => { + if (/[?#]/.test(currentValue)) { + postPath = true; } - calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { - const initialRetryDelay = 0.5; - const maxRetryDelay = 8; - const numRetries = maxRetries - retriesRemaining; - const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); - const jitter = 1 - Math.random() * 0.25; - return sleepSeconds * jitter * 1e3; - } - async buildRequest(inputOptions, { retryCount = 0 } = {}) { - const options = { ...inputOptions }; - const { method, path: path7, query, defaultBaseURL } = options; - const url = this.buildURL(path7, query, defaultBaseURL); - if ("timeout" in options) - validatePositiveInteger("timeout", options.timeout); - options.timeout = options.timeout ?? this.timeout; - const { bodyHeaders, body } = this.buildBody({ options }); - const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); - const req = { - method, - headers: reqHeaders, - ...options.signal && { signal: options.signal }, - ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" }, - ...body && { body }, - ...this.fetchOptions ?? {}, - ...options.fetchOptions ?? {} - }; - return { req, url, timeout: options.timeout }; - } - async buildHeaders({ options, method, bodyHeaders, retryCount }) { - let idempotencyHeaders = {}; - if (this.idempotencyHeader && method !== "get") { - if (!options.idempotencyKey) - options.idempotencyKey = this.defaultIdempotencyKey(); - idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; - } - const headers = buildHeaders([ - idempotencyHeaders, - { - Accept: "application/json", - "User-Agent": this.getUserAgent(), - "X-Stainless-Retry-Count": String(retryCount), - ...options.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options.timeout / 1e3)) } : {}, - ...getPlatformHeaders() - }, - await this.authHeaders(options), - this._options.defaultHeaders, - bodyHeaders, - options.headers - ]); - this.validateHeaders(headers); - return headers.values; - } - _makeAbort(controller) { - return () => controller.abort(); - } - buildBody({ options: { body, headers: rawHeaders } }) { - if (!body) { - return { bodyHeaders: void 0, body: void 0 }; - } - const headers = buildHeaders([rawHeaders]); - if ( - // Pass raw type verbatim - ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && // Preserve legacy string encoding behavior for now - headers.values.has("content-type") || // `Blob` is superset of `File` - globalThis.Blob && body instanceof globalThis.Blob || // `FormData` -> `multipart/form-data` - body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded` - body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`) - globalThis.ReadableStream && body instanceof globalThis.ReadableStream - ) { - return { bodyHeaders: void 0, body }; - } else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) { - return { bodyHeaders: void 0, body: ReadableStreamFrom(body) }; - } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") { - return { - bodyHeaders: { "content-type": "application/x-www-form-urlencoded" }, - body: this.stringifyQuery(body) - }; - } else { - return __classPrivateFieldGet(this, _BaseGitHub_encoder, "f").call(this, { body, headers }); - } + const value = params[index]; + let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value); + if (index !== params.length && (value == null || typeof value === "object" && // handle values from other realms + value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY2) ?? EMPTY2)?.toString)) { + encoded = value + ""; + invalidSegments.push({ + start: previousValue.length + currentValue.length, + length: encoded.length, + error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter` + }); } + return previousValue + currentValue + (index === params.length ? "" : encoded); + }, ""); + const pathOnly = path8.split(/[?#]/, 1)[0]; + const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; + let match; + while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) { + invalidSegments.push({ + start: match.index, + length: match[0].length, + error: `Value "${match[0]}" can't be safely passed as a path parameter` + }); } - _BaseGitHub_encoder = /* @__PURE__ */ new WeakMap(), _BaseGitHub_instances = /* @__PURE__ */ new WeakSet(), _BaseGitHub_baseURLOverridden = function _BaseGitHub_baseURLOverridden2() { - return this.baseURL !== "https://api.github.com"; - }; - BaseGitHub3.DEFAULT_TIMEOUT = 6e4; - return BaseGitHub3; -})(); + invalidSegments.sort((a, b) => a.start - b.start); + if (invalidSegments.length > 0) { + let lastEnd = 0; + const underline = invalidSegments.reduce((acc, segment) => { + const spaces = " ".repeat(segment.start - lastEnd); + const arrows = "^".repeat(segment.length); + lastEnd = segment.start + segment.length; + return acc + spaces + arrows; + }, ""); + throw new GitHubError(`Path parameters result in path with invalid segments: +${invalidSegments.map((e) => e.error).join("\n")} +${path8} +${underline}`); + } + return path8; +}; +var path2 = /* @__PURE__ */ createPathTagFunction2(encodeURIPath2); -// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/tree-shakable.mjs -function createClient(options) { - const client = new BaseGitHub(options); - for (const ResourceClass of options.resources) { - const resourceInstance = new ResourceClass(client); - let object = client; - for (const part of ResourceClass._key.slice(0, -1)) { - if (hasOwn(object, part)) { - object = object[part]; - } else { - Object.defineProperty(object, part, { - value: object = {}, - configurable: true, - enumerable: true, - writable: true - }); - } +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/resources/repos/commits/commits.mjs +var BaseCommits = /* @__PURE__ */ (() => { + class BaseCommits4 extends APIResource2 { + /** + * Returns the contents of a single commit reference. You must have `read` access + * for the repository to use this endpoint. + * + * > [!NOTE] If there are more than 300 files in the commit diff and the default + * > JSON media type is requested, the response will include pagination link + * > headers for the remaining files, up to a limit of 3000 files. Each page + * > contains the static commit information, and the only changes are to the file + * > listing. + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * Pagination query parameters are not supported for these media types. + * + * - **`application/vnd.github.diff`**: Returns the diff of the commit. Larger + * diffs may time out and return a 5xx status code. + * - **`application/vnd.github.patch`**: Returns the patch of the commit. Diffs + * with binary data will have no `patch` property. Larger diffs may time out and + * return a 5xx status code. + * - **`application/vnd.github.sha`**: Returns the commit's SHA-1 hash. You can use + * this endpoint to check if a remote reference's SHA-1 hash is the same as your + * local reference's SHA-1 hash by providing the local SHA-1 reference as the + * ETag. + * + * **Signature verification object** + * + * The response will include a `verification` object that describes the result of + * verifying the commit's signature. The following fields are included in the + * `verification` object: + * + * | Name | Type | Description | + * | ------------- | --------- | ------------------------------------------------------------------------------------------------ | + * | `verified` | `boolean` | Indicates whether GitHub considers the signature in this commit to be verified. | + * | `reason` | `string` | The reason for verified value. Possible values and their meanings are enumerated in table below. | + * | `signature` | `string` | The signature that was extracted from the commit. | + * | `payload` | `string` | The value that was signed. | + * | `verified_at` | `string` | The date the signature was verified by GitHub. | + * + * These are the possible values for `reason` in the `verification` object: + * + * | Value | Description | + * | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------- | + * | `expired_key` | The key that made the signature is expired. | + * | `not_signing_key` | The "signing" flag is not among the usage flags in the GPG key that made the signature. | + * | `gpgverify_error` | There was an error communicating with the signature verification service. | + * | `gpgverify_unavailable` | The signature verification service is currently unavailable. | + * | `unsigned` | The object does not include a signature. | + * | `unknown_signature_type` | A non-PGP signature was found in the commit. | + * | `no_user` | No user was associated with the `committer` email address in the commit. | + * | `unverified_email` | The `committer` email address in the commit was associated with a user, but the email address is not verified on their account. | + * | `bad_email` | The `committer` email address in the commit is not included in the identities of the PGP key that made the signature. | + * | `unknown_key` | The key that made the signature has not been registered with any user's account. | + * | `malformed_signature` | There was an error parsing the signature. | + * | `invalid` | The signature could not be cryptographically verified using the key whose key-id was found in the signature. | + * | `valid` | None of the above errors applied, so the signature is considered to be verified. | + * + * @example + * ```ts + * const commit = await client.repos.commits.retrieve('ref', { + * owner: 'owner', + * repo: 'repo', + * }); + * ``` + */ + retrieve(ref, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/commits/${ref}`, { query, ...options }); } - const name = ResourceClass._key.at(-1); - if (!hasOwn(object, name)) { - Object.defineProperty(object, name, { - value: resourceInstance, - configurable: true, - enumerable: true, - writable: true + /** + * **Signature verification object** + * + * The response will include a `verification` object that describes the result of + * verifying the commit's signature. The following fields are included in the + * `verification` object: + * + * | Name | Type | Description | + * | ------------- | --------- | ------------------------------------------------------------------------------------------------ | + * | `verified` | `boolean` | Indicates whether GitHub considers the signature in this commit to be verified. | + * | `reason` | `string` | The reason for verified value. Possible values and their meanings are enumerated in table below. | + * | `signature` | `string` | The signature that was extracted from the commit. | + * | `payload` | `string` | The value that was signed. | + * | `verified_at` | `string` | The date the signature was verified by GitHub. | + * + * These are the possible values for `reason` in the `verification` object: + * + * | Value | Description | + * | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------- | + * | `expired_key` | The key that made the signature is expired. | + * | `not_signing_key` | The "signing" flag is not among the usage flags in the GPG key that made the signature. | + * | `gpgverify_error` | There was an error communicating with the signature verification service. | + * | `gpgverify_unavailable` | The signature verification service is currently unavailable. | + * | `unsigned` | The object does not include a signature. | + * | `unknown_signature_type` | A non-PGP signature was found in the commit. | + * | `no_user` | No user was associated with the `committer` email address in the commit. | + * | `unverified_email` | The `committer` email address in the commit was associated with a user, but the email address is not verified on their account. | + * | `bad_email` | The `committer` email address in the commit is not included in the identities of the PGP key that made the signature. | + * | `unknown_key` | The key that made the signature has not been registered with any user's account. | + * | `malformed_signature` | There was an error parsing the signature. | + * | `invalid` | The signature could not be cryptographically verified using the key whose key-id was found in the signature. | + * | `valid` | None of the above errors applied, so the signature is considered to be verified. | + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const commit of client.repos.commits.list({ + * owner: 'owner', + * repo: 'repo', + * })) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.getAPIList(path2`/repos/${owner}/${repo}/commits`, NumberedPage, { + query, + ...options }); - } else { - if (object[name] instanceof APIResource) { - throw new TypeError(`Resource at ${ResourceClass._key.join(".")} already exists!`); - } else { - object[name] = Object.assign(resourceInstance, object[name]); - } } - } - return client; -} - -// src/compat/github/context.ts -var fs = __toESM(require("node:fs")); -var cachedContext; -function getGitHubContext() { - if (cachedContext) { - return cachedContext; - } - const [owner, repo] = process.env.GITHUB_REPOSITORY?.split("/") ?? []; - const runID = process.env.GITHUB_RUN_ID; - if (!owner || !repo || !runID) { - throw new Error( - "Expected env vars GITHUB_REPOSITORY and GITHUB_RUN_ID to be set." - ); - } - const host = process.env.GITHUB_SERVER_URL || "https://github.com"; - const apiURL = process.env.GITHUB_API_URL || "https://api.github.com"; - const runURL = `${host}/${owner}/${repo}/actions/runs/${runID}`; - let defaultBranch = null; - let prNumber = null; - try { - const eventPath = process.env.GITHUB_EVENT_PATH; - const payload = eventPath && fs.existsSync(eventPath) && JSON.parse(fs.readFileSync(eventPath, "utf-8")); - const maybeDefaultBranch = payload?.repository?.default_branch; - if (typeof maybeDefaultBranch === "string") { - defaultBranch = maybeDefaultBranch; + /** + * Protected branches are available in public repositories with GitHub Free and + * GitHub Free for organizations, and in public and private repositories with + * GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. + * For more information, see + * [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) + * in the GitHub Help documentation. + * + * Returns all branches where the given commit SHA is the HEAD, or latest commit + * for the branch. + * + * @example + * ```ts + * const response = + * await client.repos.commits.listBranchesWhereHead( + * 'commit_sha', + * { owner: 'owner', repo: 'repo' }, + * ); + * ``` + */ + listBranchesWhereHead(commitSha, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/commits/${commitSha}/branches-where-head`, options); } - const maybePRNumber = parseInt( - payload?.pull_request?.number ?? process.env.PR_NUMBER ?? "", - 10 - ); - if (Number.isInteger(maybePRNumber)) { - prNumber = maybePRNumber; + /** + * Lists check runs for a commit ref. The `ref` can be a SHA, branch name, or a tag + * name. + * + * > [!NOTE] The endpoints to manage checks only look for pushes in the repository + * > where the check suite or check run were created. Pushes to a branch in a + * > forked repository are not detected and return an empty `pull_requests` array. + * + * If there are more than 1000 check suites on a single git reference, this + * endpoint will limit check runs to the 1000 most recent check suites. To iterate + * over all possible check runs, use the + * [List check suites for a Git reference](https://docs.github.com/rest/reference/checks#list-check-suites-for-a-git-reference) + * endpoint and provide the `check_suite_id` parameter to the + * [List check runs in a check suite](https://docs.github.com/rest/reference/checks#list-check-runs-in-a-check-suite) + * endpoint. + * + * OAuth app tokens and personal access tokens (classic) need the `repo` scope to + * use this endpoint on a private repository. + * + * @example + * ```ts + * const response = await client.repos.commits.listCheckRuns( + * 'ref', + * { owner: 'owner', repo: 'repo' }, + * ); + * ``` + */ + listCheckRuns(ref, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/commits/${ref}/check-runs`, { query, ...options }); + } + /** + * Lists check suites for a commit `ref`. The `ref` can be a SHA, branch name, or a + * tag name. + * + * > [!NOTE] The endpoints to manage checks only look for pushes in the repository + * > where the check suite or check run were created. Pushes to a branch in a + * > forked repository are not detected and return an empty `pull_requests` array + * > and a `null` value for `head_branch`. + * + * OAuth app tokens and personal access tokens (classic) need the `repo` scope to + * use this endpoint on a private repository. + * + * @example + * ```ts + * const response = await client.repos.commits.listCheckSuites( + * 'ref', + * { owner: 'owner', repo: 'repo' }, + * ); + * ``` + */ + listCheckSuites(ref, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/commits/${ref}/check-suites`, { query, ...options }); + } + /** + * Lists the merged pull request that introduced the commit to the repository. If + * the commit is not present in the default branch, it will return merged and open + * pull requests associated with the commit. + * + * To list the open or merged pull requests associated with a branch, you can set + * the `commit_sha` parameter to the branch name. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const pullRequestSimple of client.repos.commits.listPullRequests( + * 'commit_sha', + * { owner: 'owner', repo: 'repo' }, + * )) { + * // ... + * } + * ``` + */ + listPullRequests(commitSha, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.getAPIList(path2`/repos/${owner}/${repo}/commits/${commitSha}/pulls`, NumberedPage, { query, ...options }); + } + /** + * Users with pull access in a repository can view commit statuses for a given ref. + * The ref can be a SHA, a branch name, or a tag name. Statuses are returned in + * reverse chronological order. The first status in the list will be the latest + * one. + * + * This resource is also available via a legacy route: + * `GET /repos/:owner/:repo/statuses/:ref`. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const commitListStatusesResponse of client.repos.commits.listStatuses( + * 'ref', + * { owner: 'owner', repo: 'repo' }, + * )) { + * // ... + * } + * ``` + */ + listStatuses(ref, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.getAPIList(path2`/repos/${owner}/${repo}/commits/${ref}/statuses`, NumberedPage, { query, ...options }); + } + /** + * Users with pull access in a repository can access a combined view of commit + * statuses for a given ref. The ref can be a SHA, a branch name, or a tag name. + * + * Additionally, a combined `state` is returned. The `state` is one of: + * + * - **failure** if any of the contexts report as `error` or `failure` + * - **pending** if there are no statuses or a context is `pending` + * - **success** if the latest status for all contexts is `success` + * + * @example + * ```ts + * const response = await client.repos.commits.retrieveStatus( + * 'ref', + * { owner: 'owner', repo: 'repo' }, + * ); + * ``` + */ + retrieveStatus(ref, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/commits/${ref}/status`, { query, ...options }); } - } catch (e) { - throw new Error(`Failed to parse GitHub event: ${e}`); } - const refName = process.env.GITHUB_REF_NAME || null; - const sha = process.env.GITHUB_SHA || null; - cachedContext = { - provider: "github", - host, - owner, - repo, - urls: { api: apiURL, run: runURL }, - names: { ci: "GitHub Actions", pr: "PR", provider: "GitHub" }, - defaultBranch, - prNumber, - refName, - sha - }; - logger.debug("GitHub context", cachedContext); - return cachedContext; -} + BaseCommits4._key = Object.freeze(["repos", "commits"]); + return BaseCommits4; +})(); -// src/compat/github/api.ts -var GitHubClient = class { - client; - constructor(token) { - this.client = createClient({ - authToken: token, - baseURL: getGitHubContext().urls.api, - owner: getGitHubContext().owner, - repo: getGitHubContext().repo, - resources: [BaseCommits, BaseComments2, BasePulls], - logLevel: "warn", - logger - }); - } - async listComments(prNumber) { - const { data } = await this.client.repos.issues.comments.list(prNumber); - return data.map((c) => ({ id: c.id, body: c.body ?? "" })); - } - async createComment(prNumber, props) { - const data = await this.client.repos.issues.comments.create( - prNumber, - props - ); - return { id: data.id, body: data.body }; - } - async updateComment(_prNumber, { id, body }) { - const data = await this.client.repos.issues.comments.update(id, { - body - }); - return { id: data.id, body: data.body }; +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/headers.mjs +var brand_privateNullableHeaders2 = /* @__PURE__ */ Symbol("brand.privateNullableHeaders"); +function* iterateHeaders2(headers) { + if (!headers) + return; + if (brand_privateNullableHeaders2 in headers) { + const { values, nulls } = headers; + yield* values.entries(); + for (const name of nulls) { + yield [name, null]; + } + return; } - async getPullRequest(number) { - const data = await this.client.repos.pulls.retrieve(number); - return { - number, - state: data.merged_at ? "merged" : data.state, - title: data.title, - base_sha: data.base.sha, - base_ref: data.base.ref, - head_ref: data.head.ref, - head_sha: data.head.sha, - merge_commit_sha: data.merge_commit_sha - }; + let shouldClear = false; + let iter; + if (headers instanceof Headers) { + iter = headers.entries(); + } else if (isReadonlyArray2(headers)) { + iter = headers; + } else { + shouldClear = true; + iter = Object.entries(headers ?? {}); } - async getPullRequestForCommit(sha) { - const pullRequests = await this.client.repos.commits.listPullRequests(sha).then( - ({ data }) => data.filter((c) => c.merged_at || c.state !== "closed") - ).catch((err) => { - if (err instanceof APIError && (err.status === 401 || err.status === 403 || err.status === 404)) { - return []; - } - throw err; - }); - if (pullRequests.length === 0) { - return null; - } - if (pullRequests.length > 1) { - logger.warn( - `Multiple pull requests found for commit; only using first.`, - { commit: sha, pulls: pullRequests.map((c) => c.number) } - ); - } - const pull = pullRequests[0]; - return { - number: pull.number, - state: pull.merged_at ? "merged" : pull.state, - title: pull.title, - base_sha: pull.base.sha, - base_ref: pull.base.ref, - head_ref: pull.head.ref, - head_sha: pull.head.sha, - merge_commit_sha: pull.merge_commit_sha - }; - } -}; -var cachedClient; -function getGitHubClient() { - if (cachedClient !== void 0) { - return cachedClient; - } - const token = getInput("github_token"); - if (token) { - cachedClient = new GitHubClient(token); - } else { - logger.info("No GitHub token found via input 'github_token'."); - cachedClient = null; - } - return cachedClient; -} - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/errors.mjs -function isAbortError2(err) { - return typeof err === "object" && err !== null && // Spec-compliant fetch implementations - ("name" in err && err.name === "AbortError" || // Expo fetch - "message" in err && String(err.message).includes("FetchRequestCanceledException")); -} -var castToError2 = (err) => { - if (err instanceof Error) - return err; - if (typeof err === "object" && err !== null) { - try { - if (Object.prototype.toString.call(err) === "[object Error]") { - const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); - if (err.stack) - error.stack = err.stack; - if (err.cause && !error.cause) - error.cause = err.cause; - if (err.name) - error.name = err.name; - return error; - } - } catch { - } - try { - return new Error(JSON.stringify(err)); - } catch { - } - } - return new Error(err); -}; - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/core/error.mjs -var GitLabError = /* @__PURE__ */ (() => { - class GitLabError2 extends Error { - } - return GitLabError2; -})(); -var APIError2 = class _APIError extends GitLabError { - constructor(status, error, message, headers) { - super(`${_APIError.makeMessage(status, error, message)}`); - this.status = status; - this.headers = headers; - this.error = error; - } - static makeMessage(status, error, message) { - const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message; - if (status && msg) { - return `${status} ${msg}`; - } - if (status) { - return `${status} status code (no body)`; - } - if (msg) { - return msg; - } - return "(no status code or body)"; - } - static generate(status, errorResponse, message, headers) { - if (!status || !headers) { - return new APIConnectionError2({ message, cause: castToError2(errorResponse) }); - } - const error = errorResponse; - if (status === 400) { - return new BadRequestError2(status, error, message, headers); - } - if (status === 401) { - return new AuthenticationError2(status, error, message, headers); - } - if (status === 403) { - return new PermissionDeniedError2(status, error, message, headers); - } - if (status === 404) { - return new NotFoundError2(status, error, message, headers); - } - if (status === 409) { - return new ConflictError2(status, error, message, headers); - } - if (status === 422) { - return new UnprocessableEntityError2(status, error, message, headers); - } - if (status === 429) { - return new RateLimitError2(status, error, message, headers); - } - if (status >= 500) { - return new InternalServerError2(status, error, message, headers); - } - return new _APIError(status, error, message, headers); - } -}; -var APIUserAbortError2 = class extends APIError2 { - constructor({ message } = {}) { - super(void 0, void 0, message || "Request was aborted.", void 0); - } -}; -var APIConnectionError2 = class extends APIError2 { - constructor({ message, cause }) { - super(void 0, void 0, message || "Connection error.", void 0); - if (cause) - this.cause = cause; - } -}; -var APIConnectionTimeoutError2 = class extends APIConnectionError2 { - constructor({ message } = {}) { - super({ message: message ?? "Request timed out." }); - } -}; -var BadRequestError2 = class extends APIError2 { -}; -var AuthenticationError2 = class extends APIError2 { -}; -var PermissionDeniedError2 = class extends APIError2 { -}; -var NotFoundError2 = class extends APIError2 { -}; -var ConflictError2 = class extends APIError2 { -}; -var UnprocessableEntityError2 = class extends APIError2 { -}; -var RateLimitError2 = class extends APIError2 { -}; -var InternalServerError2 = class extends APIError2 { -}; - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/core/resource.mjs -var APIResource2 = /* @__PURE__ */ (() => { - class APIResource4 { - constructor(client) { - this._client = client; - } - } - APIResource4._key = []; - return APIResource4; -})(); - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/utils/values.mjs -var startsWithSchemeRegexp2 = /^[a-z][a-z0-9+.-]*:/i; -var isAbsoluteURL2 = (url) => { - return startsWithSchemeRegexp2.test(url); -}; -var isArray2 = (val) => (isArray2 = Array.isArray, isArray2(val)); -var isReadonlyArray2 = isArray2; -function isEmptyObj2(obj) { - if (!obj) - return true; - for (const _k in obj) - return false; - return true; -} -function hasOwn2(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} -var validatePositiveInteger2 = (name, n) => { - if (typeof n !== "number" || !Number.isInteger(n)) { - throw new GitLabError(`${name} must be an integer`); - } - if (n < 0) { - throw new GitLabError(`${name} must be a positive integer`); - } - return n; -}; -var safeJSON2 = (text) => { - try { - return JSON.parse(text); - } catch (err) { - return void 0; - } -}; - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/headers.mjs -var brand_privateNullableHeaders2 = /* @__PURE__ */ Symbol("brand.privateNullableHeaders"); -function* iterateHeaders2(headers) { - if (!headers) - return; - if (brand_privateNullableHeaders2 in headers) { - const { values, nulls } = headers; - yield* values.entries(); - for (const name of nulls) { - yield [name, null]; - } - return; - } - let shouldClear = false; - let iter; - if (headers instanceof Headers) { - iter = headers.entries(); - } else if (isReadonlyArray2(headers)) { - iter = headers; - } else { - shouldClear = true; - iter = Object.entries(headers ?? {}); - } - for (let row of iter) { - const name = row[0]; - if (typeof name !== "string") - throw new TypeError("expected header name to be a string"); - const values = isReadonlyArray2(row[1]) ? row[1] : [row[1]]; - let didClear = false; - for (const value of values) { - if (value === void 0) - continue; - if (shouldClear && !didClear) { - didClear = true; - yield [name, null]; + for (let row of iter) { + const name = row[0]; + if (typeof name !== "string") + throw new TypeError("expected header name to be a string"); + const values = isReadonlyArray2(row[1]) ? row[1] : [row[1]]; + let didClear = false; + for (const value of values) { + if (value === void 0) + continue; + if (shouldClear && !didClear) { + didClear = true; + yield [name, null]; } yield [name, value]; } @@ -13582,728 +12114,776 @@ var buildHeaders2 = (newHeaders) => { return { [brand_privateNullableHeaders2]: true, values: targetHeaders, nulls: nullHeaders }; }; -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/utils/path.mjs -function encodeURIPath2(str) { - return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); -} -var EMPTY2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); -var createPathTagFunction2 = (pathEncoder = encodeURIPath2) => function path7(statics, ...params) { - if (statics.length === 1) - return statics[0]; - let postPath = false; - const invalidSegments = []; - const path8 = statics.reduce((previousValue, currentValue, index) => { - if (/[?#]/.test(currentValue)) { - postPath = true; - } - const value = params[index]; - let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value); - if (index !== params.length && (value == null || typeof value === "object" && // handle values from other realms - value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY2) ?? EMPTY2)?.toString)) { - encoded = value + ""; - invalidSegments.push({ - start: previousValue.length + currentValue.length, - length: encoded.length, - error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter` - }); - } - return previousValue + currentValue + (index === params.length ? "" : encoded); - }, ""); - const pathOnly = path8.split(/[?#]/, 1)[0]; - const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; - let match; - while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) { - invalidSegments.push({ - start: match.index, - length: match[0].length, - error: `Value "${match[0]}" can't be safely passed as a path parameter` - }); - } - invalidSegments.sort((a, b) => a.start - b.start); - if (invalidSegments.length > 0) { - let lastEnd = 0; - const underline = invalidSegments.reduce((acc, segment) => { - const spaces = " ".repeat(segment.start - lastEnd); - const arrows = "^".repeat(segment.length); - lastEnd = segment.start + segment.length; - return acc + spaces + arrows; - }, ""); - throw new GitLabError(`Path parameters result in path with invalid segments: -${invalidSegments.map((e) => e.error).join("\n")} -${path8} -${underline}`); - } - return path8; -}; -var path2 = /* @__PURE__ */ createPathTagFunction2(encodeURIPath2); - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/resources/projects/merge-requests/notes/notes.mjs -var BaseNotes2 = /* @__PURE__ */ (() => { - class BaseNotes13 extends APIResource2 { +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/resources/repos/issues/comments/comments.mjs +var BaseComments2 = /* @__PURE__ */ (() => { + class BaseComments8 extends APIResource2 { /** - * Create a new merge request note + * You can use the REST API to create comments on issues and pull requests. Every + * pull request is an issue, but not every issue is a pull request. + * + * This endpoint triggers + * [notifications](https://docs.github.com/github/managing-subscriptions-and-notifications-on-github/about-notifications). + * Creating content too quickly using this endpoint may result in secondary rate + * limiting. For more information, see + * "[Rate limits for the API](https://docs.github.com/rest/using-the-rest-api/rate-limits-for-the-rest-api#about-secondary-rate-limits)" + * and + * "[Best practices for using the REST API](https://docs.github.com/rest/guides/best-practices-for-using-the-rest-api)." + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response + * will include `body`. This is the default if you do not pass any specific media + * type. + * - **`application/vnd.github.text+json`**: Returns a text only representation of + * the markdown body. Response will include `body_text`. + * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's + * markdown. Response will include `body_html`. + * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML + * representations. Response will include `body`, `body_text`, and `body_html`. * * @example * ```ts - * const apiEntitiesNote = - * await client.projects.mergeRequests.notes.create(0, { - * id: 'id', - * body: 'body', + * const issueComment = + * await client.repos.issues.comments.create(0, { + * owner: 'owner', + * repo: 'repo', + * body: 'Me too', * }); * ``` */ - create(noteableID, params, options) { - const { id, ...body } = params; - return this._client.post(path2`/projects/${id}/merge_requests/${noteableID}/notes`, { body, ...options }); + create(issueNumber, params, options) { + const { owner = this._client.owner, repo = this._client.repo, ...body } = params; + return this._client.post(path2`/repos/${owner}/${repo}/issues/${issueNumber}/comments`, { + body, + ...options + }); } /** - * Get a single merge request note + * You can use the REST API to get comments on issues and pull requests. Every pull + * request is an issue, but not every issue is a pull request. + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response + * will include `body`. This is the default if you do not pass any specific media + * type. + * - **`application/vnd.github.text+json`**: Returns a text only representation of + * the markdown body. Response will include `body_text`. + * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's + * markdown. Response will include `body_html`. + * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML + * representations. Response will include `body`, `body_text`, and `body_html`. * * @example * ```ts - * const apiEntitiesNote = - * await client.projects.mergeRequests.notes.retrieve(0, { - * id: 'id', - * noteable_id: 0, + * const issueComment = + * await client.repos.issues.comments.retrieve(0, { + * owner: 'owner', + * repo: 'repo', * }); * ``` */ - retrieve(noteID, params, options) { - const { id, noteable_id } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${noteable_id}/notes/${noteID}`, options); + retrieve(commentID, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/issues/comments/${commentID}`, options); } /** - * Update an existing merge request note + * You can use the REST API to update comments on issues and pull requests. Every + * pull request is an issue, but not every issue is a pull request. + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response + * will include `body`. This is the default if you do not pass any specific media + * type. + * - **`application/vnd.github.text+json`**: Returns a text only representation of + * the markdown body. Response will include `body_text`. + * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's + * markdown. Response will include `body_html`. + * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML + * representations. Response will include `body`, `body_text`, and `body_html`. * * @example * ```ts - * const apiEntitiesNote = - * await client.projects.mergeRequests.notes.update(0, { - * id: 'id', - * noteable_id: 0, + * const issueComment = + * await client.repos.issues.comments.update(0, { + * owner: 'owner', + * repo: 'repo', + * body: 'Me too', * }); * ``` */ - update(noteID, params, options) { - const { id, noteable_id, ...body } = params; - return this._client.put(path2`/projects/${id}/merge_requests/${noteable_id}/notes/${noteID}`, { + update(commentID, params, options) { + const { owner = this._client.owner, repo = this._client.repo, ...body } = params; + return this._client.patch(path2`/repos/${owner}/${repo}/issues/comments/${commentID}`, { body, ...options }); } + async upsertBasedOnBodyMatch(issueNumber, { bodyIncludes, createParams, updateParams, options }) { + const comments = await this.list(issueNumber); + const match = comments.data.find((comment) => comment.body?.includes(bodyIncludes)); + if (match) { + return this.update(match.id, updateParams, options); + } else { + return this.create(issueNumber, createParams, options); + } + } /** - * Get a list of merge request notes + * You can use the REST API to list comments on issues and pull requests. Every + * pull request is an issue, but not every issue is a pull request. + * + * Issue comments are ordered by ascending ID. + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response + * will include `body`. This is the default if you do not pass any specific media + * type. + * - **`application/vnd.github.text+json`**: Returns a text only representation of + * the markdown body. Response will include `body_text`. + * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's + * markdown. Response will include `body_html`. + * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML + * representations. Response will include `body`, `body_text`, and `body_html`. * * @example * ```ts - * const apiEntitiesNote = - * await client.projects.mergeRequests.notes.list(0, { - * id: 'id', - * }); + * // Automatically fetches more pages as needed. + * for await (const issueComment of client.repos.issues.comments.list( + * 0, + * { owner: 'owner', repo: 'repo' }, + * )) { + * // ... + * } * ``` */ - list(noteableID, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${noteableID}/notes`, { query, ...options }); + list(issueNumber, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.getAPIList(path2`/repos/${owner}/${repo}/issues/${issueNumber}/comments`, NumberedPage, { query, ...options }); } /** - * Delete a merge request note + * You can use the REST API to delete comments on issues and pull requests. Every + * pull request is an issue, but not every issue is a pull request. * * @example * ```ts - * const apiEntitiesNote = - * await client.projects.mergeRequests.notes.delete(0, { - * id: 'id', - * noteable_id: 0, - * }); + * await client.repos.issues.comments.delete(0, { + * owner: 'owner', + * repo: 'repo', + * }); * ``` */ - delete(noteID, params, options) { - const { id, noteable_id } = params; - return this._client.delete(path2`/projects/${id}/merge_requests/${noteable_id}/notes/${noteID}`, options); + delete(commentID, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; + return this._client.delete(path2`/repos/${owner}/${repo}/issues/comments/${commentID}`, { + ...options, + headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + }); } } - BaseNotes13._key = Object.freeze([ - "projects", - "mergeRequests", - "notes" + BaseComments8._key = Object.freeze([ + "repos", + "issues", + "comments" ]); - return BaseNotes13; + return BaseComments8; })(); -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/resources/projects/merge-requests/merge-requests.mjs -var BaseMergeRequests = /* @__PURE__ */ (() => { - class BaseMergeRequests3 extends APIResource2 { +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/resources/repos/pulls/pulls.mjs +var BasePulls = /* @__PURE__ */ (() => { + class BasePulls2 extends APIResource2 { /** - * Create a new merge request. + * Draft pull requests are available in public repositories with GitHub Free and + * GitHub Free for organizations, GitHub Pro, and legacy per-repository billing + * plans, and in public and private repositories with GitHub Team and GitHub + * Enterprise Cloud. For more information, see + * [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) + * in the GitHub Help documentation. + * + * To open or update a pull request in a public repository, you must have write + * access to the head or the source branch. For organization-owned repositories, + * you must be a member of the organization that owns the repository to open or + * update a pull request. + * + * This endpoint triggers + * [notifications](https://docs.github.com/github/managing-subscriptions-and-notifications-on-github/about-notifications). + * Creating content too quickly using this endpoint may result in secondary rate + * limiting. For more information, see + * "[Rate limits for the API](https://docs.github.com/rest/using-the-rest-api/rate-limits-for-the-rest-api#about-secondary-rate-limits)" + * and + * "[Best practices for using the REST API](https://docs.github.com/rest/guides/best-practices-for-using-the-rest-api)." + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response + * will include `body`. This is the default if you do not pass any specific media + * type. + * - **`application/vnd.github.text+json`**: Returns a text only representation of + * the markdown body. Response will include `body_text`. + * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's + * markdown. Response will include `body_html`. + * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML + * representations. Response will include `body`, `body_text`, and `body_html`. * * @example * ```ts - * const apiEntitiesMergeRequest = - * await client.projects.mergeRequests.create('string', { - * source_branch: 'source_branch', - * target_branch: 'target_branch', - * title: 'title', - * }); + * const pullRequest = await client.repos.pulls.create({ + * owner: 'owner', + * repo: 'repo', + * base: 'master', + * head: 'octocat:new-feature', + * body: 'Please pull these awesome changes in!', + * title: 'Amazing new feature', + * }); * ``` */ - create(id, body, options) { - return this._client.post(path2`/projects/${id}/merge_requests`, { body, ...options }); + create(params, options) { + const { owner = this._client.owner, repo = this._client.repo, ...body } = params; + return this._client.post(path2`/repos/${owner}/${repo}/pulls`, { body, ...options }); } /** - * Shows information about a single merge request. Note: the `changes_count` value - * in the response is a string, not an integer. This is because when an merge - * request has too many changes to display and store, it is capped at 1,000. In - * that case, the API returns the string `"1000+"` for the changes count. + * Draft pull requests are available in public repositories with GitHub Free and + * GitHub Free for organizations, GitHub Pro, and legacy per-repository billing + * plans, and in public and private repositories with GitHub Team and GitHub + * Enterprise Cloud. For more information, see + * [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) + * in the GitHub Help documentation. + * + * Lists details of a pull request by providing its number. + * + * When you get, + * [create](https://docs.github.com/rest/pulls/pulls/#create-a-pull-request), or + * [edit](https://docs.github.com/rest/pulls/pulls#update-a-pull-request) a pull + * request, GitHub creates a merge commit to test whether the pull request can be + * automatically merged into the base branch. This test commit is not added to the + * base branch or the head branch. You can review the status of the test commit + * using the `mergeable` key. For more information, see + * "[Checking mergeability of pull requests](https://docs.github.com/rest/guides/getting-started-with-the-git-database-api#checking-mergeability-of-pull-requests)". + * + * The value of the `mergeable` attribute can be `true`, `false`, or `null`. If the + * value is `null`, then GitHub has started a background job to compute the + * mergeability. After giving the job time to complete, resubmit the request. When + * the job finishes, you will see a non-`null` value for the `mergeable` attribute + * in the response. If `mergeable` is `true`, then `merge_commit_sha` will be the + * SHA of the _test_ merge commit. + * + * The value of the `merge_commit_sha` attribute changes depending on the state of + * the pull request. Before merging a pull request, the `merge_commit_sha` + * attribute holds the SHA of the _test_ merge commit. After merging a pull + * request, the `merge_commit_sha` attribute changes depending on how you merged + * the pull request: + * + * - If merged as a + * [merge commit](https://docs.github.com/articles/about-merge-methods-on-github/), + * `merge_commit_sha` represents the SHA of the merge commit. + * - If merged via a + * [squash](https://docs.github.com/articles/about-merge-methods-on-github/#squashing-your-merge-commits), + * `merge_commit_sha` represents the SHA of the squashed commit on the base + * branch. + * - If + * [rebased](https://docs.github.com/articles/about-merge-methods-on-github/#rebasing-and-merging-your-commits), + * `merge_commit_sha` represents the commit that the base branch was updated to. + * + * Pass the appropriate + * [media type](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types) + * to fetch diff and patch formats. + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response + * will include `body`. This is the default if you do not pass any specific media + * type. + * - **`application/vnd.github.text+json`**: Returns a text only representation of + * the markdown body. Response will include `body_text`. + * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's + * markdown. Response will include `body_html`. + * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML + * representations. Response will include `body`, `body_text`, and `body_html`. + * - **`application/vnd.github.diff`**: For more information, see + * "[git-diff](https://git-scm.com/docs/git-diff)" in the Git documentation. If a + * diff is corrupt, contact us through the + * [GitHub Support portal](https://support.github.com/). Include the repository + * name and pull request ID in your message. * * @example * ```ts - * const apiEntitiesMergeRequest = - * await client.projects.mergeRequests.retrieve(0, { - * id: 'string', - * }); + * const pullRequest = await client.repos.pulls.retrieve(0, { + * owner: 'owner', + * repo: 'repo', + * }); * ``` */ - retrieve(mergeRequestIid, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${mergeRequestIid}`, { query, ...options }); + retrieve(pullNumber, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/pulls/${pullNumber}`, options); } /** - * Updates an existing merge request. You can change the target branch, title, or - * even close the merge request. + * Draft pull requests are available in public repositories with GitHub Free and + * GitHub Free for organizations, GitHub Pro, and legacy per-repository billing + * plans, and in public and private repositories with GitHub Team and GitHub + * Enterprise Cloud. For more information, see + * [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) + * in the GitHub Help documentation. + * + * To open or update a pull request in a public repository, you must have write + * access to the head or the source branch. For organization-owned repositories, + * you must be a member of the organization that owns the repository to open or + * update a pull request. + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response + * will include `body`. This is the default if you do not pass any specific media + * type. + * - **`application/vnd.github.text+json`**: Returns a text only representation of + * the markdown body. Response will include `body_text`. + * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's + * markdown. Response will include `body_html`. + * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML + * representations. Response will include `body`, `body_text`, and `body_html`. * * @example * ```ts - * const apiEntitiesMergeRequest = - * await client.projects.mergeRequests.update(0, { - * id: 'string', - * }); + * const pullRequest = await client.repos.pulls.update(0, { + * owner: 'owner', + * repo: 'repo', + * base: 'master', + * body: 'updated body', + * state: 'open', + * title: 'new title', + * }); * ``` */ - update(mergeRequestIid, params, options) { - const { id, ...body } = params; - return this._client.put(path2`/projects/${id}/merge_requests/${mergeRequestIid}`, { body, ...options }); + update(pullNumber, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...body } = params ?? {}; + return this._client.patch(path2`/repos/${owner}/${repo}/pulls/${pullNumber}`, { body, ...options }); } /** - * Get all merge requests for this project. + * Lists pull requests in a specified repository. + * + * Draft pull requests are available in public repositories with GitHub Free and + * GitHub Free for organizations, GitHub Pro, and legacy per-repository billing + * plans, and in public and private repositories with GitHub Team and GitHub + * Enterprise Cloud. For more information, see + * [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) + * in the GitHub Help documentation. + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response + * will include `body`. This is the default if you do not pass any specific media + * type. + * - **`application/vnd.github.text+json`**: Returns a text only representation of + * the markdown body. Response will include `body_text`. + * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's + * markdown. Response will include `body_html`. + * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML + * representations. Response will include `body`, `body_text`, and `body_html`. * * @example * ```ts - * const apiEntitiesMergeRequestBasics = - * await client.projects.mergeRequests.list('string'); + * // Automatically fetches more pages as needed. + * for await (const pullRequestSimple of client.repos.pulls.list( + * { owner: 'owner', repo: 'repo' }, + * )) { + * // ... + * } * ``` */ - list(id, query = {}, options) { - return this._client.get(path2`/projects/${id}/merge_requests`, { query, ...options }); + list(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.getAPIList(path2`/repos/${owner}/${repo}/pulls`, NumberedPage, { + query, + ...options + }); } /** - * Only for administrators and project owners. Deletes the merge request in - * question. + * Creates a codespace owned by the authenticated user for the specified pull + * request. + * + * OAuth app tokens and personal access tokens (classic) need the `codespace` scope + * to use this endpoint. * * @example * ```ts - * await client.projects.mergeRequests.delete(0, { - * id: 'string', - * }); + * const codespace = await client.repos.pulls.createCodespace( + * 0, + * { owner: 'owner', repo: 'repo' }, + * ); * ``` */ - delete(mergeRequestIid, params, options) { - const { id } = params; - return this._client.delete(path2`/projects/${id}/merge_requests/${mergeRequestIid}`, { - ...options, - headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + createCodespace(pullNumber, params, options) { + const { owner = this._client.owner, repo = this._client.repo, ...body } = params; + return this._client.post(path2`/repos/${owner}/${repo}/pulls/${pullNumber}/codespaces`, { + body, + ...options }); } /** - * Adds spent time for this merge_request. + * Creates a review comment on the diff of a specified pull request. To add a + * regular comment to a pull request timeline, see + * "[Create an issue comment](https://docs.github.com/rest/issues/comments#create-an-issue-comment)." + * + * If your comment applies to more than one line in the pull request diff, you + * should use the parameters `line`, `side`, and optionally `start_line` and + * `start_side` in your request. + * + * The `position` parameter is closing down. If you use `position`, the `line`, + * `side`, `start_line`, and `start_side` parameters are not required. + * + * This endpoint triggers + * [notifications](https://docs.github.com/github/managing-subscriptions-and-notifications-on-github/about-notifications). + * Creating content too quickly using this endpoint may result in secondary rate + * limiting. For more information, see + * "[Rate limits for the API](https://docs.github.com/rest/using-the-rest-api/rate-limits-for-the-rest-api#about-secondary-rate-limits)" + * and + * "[Best practices for using the REST API](https://docs.github.com/rest/guides/best-practices-for-using-the-rest-api)." + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github-commitcomment.raw+json`**: Returns the raw markdown + * body. Response will include `body`. This is the default if you do not pass any + * specific media type. + * - **`application/vnd.github-commitcomment.text+json`**: Returns a text only + * representation of the markdown body. Response will include `body_text`. + * - **`application/vnd.github-commitcomment.html+json`**: Returns HTML rendered + * from the body's markdown. Response will include `body_html`. + * - **`application/vnd.github-commitcomment.full+json`**: Returns raw, text, and + * HTML representations. Response will include `body`, `body_text`, and + * `body_html`. * * @example * ```ts - * const apiEntitiesIssuableTimeStats = - * await client.projects.mergeRequests.addSpentTime(0, { - * id: 'string', - * duration: 'duration', - * }); + * const response = await client.repos.pulls.createComment(0, { + * owner: 'owner', + * repo: 'repo', + * body: 'Great stuff!', + * commit_id: '6dcb09b5b57875f334f61aebed695e2e4193db5e', + * path: 'file1.txt', + * line: 2, + * side: 'RIGHT', + * start_line: 1, + * start_side: 'RIGHT', + * }); * ``` */ - addSpentTime(mergeRequestIid, params, options) { - const { id, ...body } = params; - return this._client.post(path2`/projects/${id}/merge_requests/${mergeRequestIid}/add_spent_time`, { + createComment(pullNumber, params, options) { + const { owner = this._client.owner, repo = this._client.repo, ...body } = params; + return this._client.post(path2`/repos/${owner}/${repo}/pulls/${pullNumber}/comments`, { body, ...options }); } /** - * Approve a merge request + * Lists all review comments for a specified pull request. By default, review + * comments are in ascending order by ID. * - * @example - * ```ts - * const apiEntitiesMergeRequestApprovals = - * await client.projects.mergeRequests.approve(0, { - * id: 'id', - * }); - * ``` - */ - approve(mergeRequestIid, params, options) { - const { id, ...body } = params; - return this._client.post(path2`/projects/${id}/merge_requests/${mergeRequestIid}/approve`, { - body, - ...options - }); - } - /** - * Cancel merge if "Merge When Pipeline Succeeds" is enabled - * - * @example - * ```ts - * const apiEntitiesMergeRequest = - * await client.projects.mergeRequests.cancelMergeWhenPipelineSucceeds( - * 0, - * { id: 'string' }, - * ); - * ``` - */ - cancelMergeWhenPipelineSucceeds(mergeRequestIid, params, options) { - const { id } = params; - return this._client.post(path2`/projects/${id}/merge_requests/${mergeRequestIid}/cancel_merge_when_pipeline_succeeds`, options); - } - /** - * Resets the total spent time for this merge_request to 0 seconds. - * - * @example - * ```ts - * const apiEntitiesIssuableTimeStats = - * await client.projects.mergeRequests.resetSpentTime(0, { - * id: 'string', - * }); - * ``` - */ - resetSpentTime(mergeRequestIid, params, options) { - const { id } = params; - return this._client.post(path2`/projects/${id}/merge_requests/${mergeRequestIid}/reset_spent_time`, options); - } - /** - * Resets the estimated time for this merge_request to 0 seconds. + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." * - * @example - * ```ts - * const apiEntitiesIssuableTimeStats = - * await client.projects.mergeRequests.resetTimeEstimate(0, { - * id: 'string', - * }); - * ``` - */ - resetTimeEstimate(mergeRequestIid, params, options) { - const { id } = params; - return this._client.post(path2`/projects/${id}/merge_requests/${mergeRequestIid}/reset_time_estimate`, options); - } - /** - * List approval rules for merge request + * - **`application/vnd.github-commitcomment.raw+json`**: Returns the raw markdown + * body. Response will include `body`. This is the default if you do not pass any + * specific media type. + * - **`application/vnd.github-commitcomment.text+json`**: Returns a text only + * representation of the markdown body. Response will include `body_text`. + * - **`application/vnd.github-commitcomment.html+json`**: Returns HTML rendered + * from the body's markdown. Response will include `body_html`. + * - **`application/vnd.github-commitcomment.full+json`**: Returns raw, text, and + * HTML representations. Response will include `body`, `body_text`, and + * `body_html`. * * @example * ```ts - * await client.projects.mergeRequests.retrieveApprovalSettings( + * // Automatically fetches more pages as needed. + * for await (const pullListCommentsResponse of client.repos.pulls.listComments( * 0, - * { id: 'string' }, - * ); + * { owner: 'owner', repo: 'repo' }, + * )) { + * // ... + * } * ``` */ - retrieveApprovalSettings(mergeRequestIid, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${mergeRequestIid}/approval_settings`, { - query, - ...options, - headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) - }); + listComments(pullNumber, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.getAPIList(path2`/repos/${owner}/${repo}/pulls/${pullNumber}/comments`, NumberedPage, { query, ...options }); } /** - * Get approval state of merge request + * Lists a maximum of 250 commits for a pull request. To receive a complete commit + * list for pull requests with more than 250 commits, use the + * [List commits](https://docs.github.com/rest/commits/commits#list-commits) + * endpoint. * - * @example - * ```ts - * const response = - * await client.projects.mergeRequests.retrieveApprovalState( - * 0, - * { id: 'string' }, - * ); - * ``` - */ - retrieveApprovalState(mergeRequestIid, params, options) { - const { id } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${mergeRequestIid}/approval_state`, options); - } - /** - * Get all merge requests are blockees for this merge request + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." * - * @example - * ```ts - * const apiEntitiesMergeRequestDependency = - * await client.projects.mergeRequests.retrieveBlockees(0, { - * id: 'string', - * }); - * ``` - */ - retrieveBlockees(mergeRequestIid, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${mergeRequestIid}/blockees`, { - query, - ...options - }); - } - /** - * Shows information about the merge request including its files and changes. + * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response + * will include `body`. This is the default if you do not pass any specific media + * type. + * - **`application/vnd.github.text+json`**: Returns a text only representation of + * the markdown body. Response will include `body_text`. + * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's + * markdown. Response will include `body_html`. + * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML + * representations. Response will include `body`, `body_text`, and `body_html`. * * @example * ```ts - * const response = - * await client.projects.mergeRequests.retrieveChanges(0, { - * id: 'string', - * }); + * // Automatically fetches more pages as needed. + * for await (const commit of client.repos.pulls.listCommits( + * 0, + * { owner: 'owner', repo: 'repo' }, + * )) { + * // ... + * } * ``` */ - retrieveChanges(mergeRequestIid, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${mergeRequestIid}/changes`, { - query, - ...options - }); + listCommits(pullNumber, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.getAPIList(path2`/repos/${owner}/${repo}/pulls/${pullNumber}/commits`, NumberedPage, { query, ...options }); } /** - * Get all the issues that would be closed by merging the provided merge request. + * Lists the files in a specified pull request. * - * @example - * ```ts - * const response = - * await client.projects.mergeRequests.retrieveClosesIssues( - * 0, - * { id: 'string' }, - * ); - * ``` - */ - retrieveClosesIssues(mergeRequestIid, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${mergeRequestIid}/closes_issues`, { - query, - ...options - }); - } - /** - * Get a list of merge request commits. + * > [!NOTE] Responses include a maximum of 3000 files. The paginated response + * > returns 30 files per page by default. * - * @example - * ```ts - * const apiEntitiesCommit = - * await client.projects.mergeRequests.retrieveCommits(0, { - * id: 'string', - * }); - * ``` - */ - retrieveCommits(mergeRequestIid, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${mergeRequestIid}/commits`, { - query, - ...options - }); - } - /** - * Get a list of merge request diffs. + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response + * will include `body`. This is the default if you do not pass any specific media + * type. + * - **`application/vnd.github.text+json`**: Returns a text only representation of + * the markdown body. Response will include `body_text`. + * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's + * markdown. Response will include `body_html`. + * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML + * representations. Response will include `body`, `body_text`, and `body_html`. * * @example * ```ts - * const apiEntitiesDiff = - * await client.projects.mergeRequests.retrieveDiffs(0, { - * id: 'string', - * }); + * // Automatically fetches more pages as needed. + * for await (const pullListFilesResponse of client.repos.pulls.listFiles( + * 0, + * { owner: 'owner', repo: 'repo' }, + * )) { + * // ... + * } * ``` */ - retrieveDiffs(mergeRequestIid, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${mergeRequestIid}/diffs`, { - query, - ...options - }); + listFiles(pullNumber, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.getAPIList(path2`/repos/${owner}/${repo}/pulls/${pullNumber}/files`, NumberedPage, { query, ...options }); } /** - * Returns the up to date merge-ref HEAD commit + * Updates the pull request branch with the latest upstream changes by merging HEAD + * from the base branch into the pull request branch. Note: If making a request on + * behalf of a GitHub App you must also have permissions to write the contents of + * the head repository. * * @example * ```ts - * await client.projects.mergeRequests.retrieveMergeRef(0, { - * id: 'string', + * const response = await client.repos.pulls.updateBranch(0, { + * owner: 'owner', + * repo: 'repo', + * expected_head_sha: + * '6dcb09b5b57875f334f61aebed695e2e4193db5e', * }); * ``` */ - retrieveMergeRef(mergeRequestIid, params, options) { - const { id } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${mergeRequestIid}/merge_ref`, { - ...options, - headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) - }); - } - /** - * Get a list of merge request participants. - * - * @example - * ```ts - * const apiEntitiesUserBasic = - * await client.projects.mergeRequests.retrieveParticipants( - * 0, - * { id: 'string' }, - * ); - * ``` - */ - retrieveParticipants(mergeRequestIid, params, options) { - const { id } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${mergeRequestIid}/participants`, options); - } - /** - * Get the raw diffs of a merge request that can used programmatically. - * - * @example - * ```ts - * await client.projects.mergeRequests.retrieveRawDiffs(0, { - * id: 'string', - * }); - * ``` - */ - retrieveRawDiffs(mergeRequestIid, params, options) { - const { id } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${mergeRequestIid}/raw_diffs`, { - ...options, - headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) - }); - } - /** - * Get all the related issues from title, description, commits, comments and - * discussions of the merge request. - * - * @example - * ```ts - * await client.projects.mergeRequests.retrieveRelatedIssues( - * 0, - * { id: 'string' }, - * ); - * ``` - */ - retrieveRelatedIssues(mergeRequestIid, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${mergeRequestIid}/related_issues`, { - query, - ...options, - headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) - }); - } - /** - * Get a list of merge request reviewers. - * - * @example - * ```ts - * const response = - * await client.projects.mergeRequests.retrieveReviewers(0, { - * id: 'string', - * }); - * ``` - */ - retrieveReviewers(mergeRequestIid, params, options) { - const { id } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${mergeRequestIid}/reviewers`, options); - } - /** - * Get time tracking stats - * - * @example - * ```ts - * const apiEntitiesIssuableTimeStats = - * await client.projects.mergeRequests.retrieveTimeStats(0, { - * id: 'string', - * }); - * ``` - */ - retrieveTimeStats(mergeRequestIid, params, options) { - const { id } = params; - return this._client.get(path2`/projects/${id}/merge_requests/${mergeRequestIid}/time_stats`, options); - } - /** - * Set status of an external status check - * - * @example - * ```ts - * const response = - * await client.projects.mergeRequests.statusCheckResponses( - * 1, - * { - * id: '1', - * external_status_check_id: 1, - * sha: '5957a570eee0ac4580ec027fb874ad7514d1e576', - * status: 'passed', - * }, - * ); - * ``` - */ - statusCheckResponses(mergeRequestIid, params, options) { - const { id, ...body } = params; - return this._client.post(path2`/projects/${id}/merge_requests/${mergeRequestIid}/status_check_responses`, { - body, - ...options - }); - } - /** - * Subscribe to a resource - * - * @example - * ```ts - * const apiEntitiesMergeRequest = - * await client.projects.mergeRequests.subscribe( - * 'subscribable_id', - * { id: 'id' }, - * ); - * ``` - */ - subscribe(subscribableID, params, options) { - const { id } = params; - return this._client.post(path2`/projects/${id}/merge_requests/${subscribableID}/subscribe`, options); - } - /** - * Sets an estimated time of work for this merge_request. - * - * @example - * ```ts - * const apiEntitiesIssuableTimeStats = - * await client.projects.mergeRequests.timeEstimate(0, { - * id: 'string', - * duration: '3h30m', - * }); - * ``` - */ - timeEstimate(mergeRequestIid, params, options) { - const { id, ...body } = params; - return this._client.post(path2`/projects/${id}/merge_requests/${mergeRequestIid}/time_estimate`, { - body, - ...options - }); - } - /** - * Create a to-do item on an issuable - * - * @example - * ```ts - * const apiEntitiesTodo = - * await client.projects.mergeRequests.todo(0, { id: 'id' }); - * ``` - */ - todo(mergeRequestIid, params, options) { - const { id } = params; - return this._client.post(path2`/projects/${id}/merge_requests/${mergeRequestIid}/todo`, options); - } - /** - * Remove an approval from a merge request - * - * @example - * ```ts - * const apiEntitiesMergeRequestApprovals = - * await client.projects.mergeRequests.unapprove(0, { - * id: 'id', - * }); - * ``` - */ - unapprove(mergeRequestIid, params, options) { - const { id } = params; - return this._client.post(path2`/projects/${id}/merge_requests/${mergeRequestIid}/unapprove`, options); - } - /** - * Unsubscribe from a resource - * - * @example - * ```ts - * const apiEntitiesMergeRequest = - * await client.projects.mergeRequests.unsubscribe( - * 'subscribable_id', - * { id: 'id' }, - * ); - * ``` - */ - unsubscribe(subscribableID, params, options) { - const { id } = params; - return this._client.post(path2`/projects/${id}/merge_requests/${subscribableID}/unsubscribe`, options); - } - /** - * Accept and merge changes submitted with the merge request using this API. - * - * @example - * ```ts - * const apiEntitiesMergeRequest = - * await client.projects.mergeRequests.updateMerge(0, { - * id: 'string', - * }); - * ``` - */ - updateMerge(mergeRequestIid, params, options) { - const { id, ...body } = params; - return this._client.put(path2`/projects/${id}/merge_requests/${mergeRequestIid}/merge`, { - body, - ...options - }); - } - /** - * Automatically rebase the `source_branch` of the merge request against its - * `target_branch`. This feature was added in GitLab 11.6 - * - * @example - * ```ts - * await client.projects.mergeRequests.updateRebase(0, { - * id: 'string', - * }); - * ``` - */ - updateRebase(mergeRequestIid, params, options) { - const { id, ...body } = params; - return this._client.put(path2`/projects/${id}/merge_requests/${mergeRequestIid}/rebase`, { - body, - ...options, - headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) - }); - } - /** - * Clear all approvals of merge request. This feature was added in GitLab 15.4 - * - * @example - * ```ts - * await client.projects.mergeRequests.updateResetApprovals( - * 0, - * { id: 'id' }, - * ); - * ``` - */ - updateResetApprovals(mergeRequestIid, params, options) { - const { id } = params; - return this._client.put(path2`/projects/${id}/merge_requests/${mergeRequestIid}/reset_approvals`, { - ...options, - headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + updateBranch(pullNumber, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...body } = params ?? {}; + return this._client.put(path2`/repos/${owner}/${repo}/pulls/${pullNumber}/update-branch`, { + body, + ...options }); } } - BaseMergeRequests3._key = Object.freeze([ - "projects", - "mergeRequests" - ]); - return BaseMergeRequests3; + BasePulls2._key = Object.freeze(["repos", "pulls"]); + return BasePulls2; })(); -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/shims.mjs -function getDefaultFetch2() { - if (typeof fetch !== "undefined") { - return fetch; +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/utils/uuid.mjs +var uuid42 = function() { + const { crypto: crypto2 } = globalThis; + if (crypto2?.randomUUID) { + uuid42 = crypto2.randomUUID.bind(crypto2); + return crypto2.randomUUID(); } - throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new GitLab({ fetch })` or polyfill the global, `globalThis.fetch = fetch`"); -} -function makeReadableStream2(...args) { - const ReadableStream = globalThis.ReadableStream; - if (typeof ReadableStream === "undefined") { - throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`"); + const u8 = new Uint8Array(1); + const randomByte = crypto2 ? () => crypto2.getRandomValues(u8)[0] : () => Math.random() * 255 & 255; + return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16)); +}; + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/utils/sleep.mjs +var sleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/version.mjs +var VERSION2 = "0.25.1"; + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/detect-platform.mjs +function getDetectedPlatform2() { + if (typeof Deno !== "undefined" && Deno.build != null) { + return "deno"; } - return new ReadableStream(...args); + if (typeof EdgeRuntime !== "undefined") { + return "edge"; + } + if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") { + return "node"; + } + return "unknown"; } -function ReadableStreamFrom2(iterable) { +var getPlatformProperties2 = () => { + const detectedPlatform = getDetectedPlatform2(); + if (detectedPlatform === "deno") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION2, + "X-Stainless-OS": normalizePlatform2(Deno.build.os), + "X-Stainless-Arch": normalizeArch2(Deno.build.arch), + "X-Stainless-Runtime": "deno", + "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown" + }; + } + if (typeof EdgeRuntime !== "undefined") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION2, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": `other:${EdgeRuntime}`, + "X-Stainless-Runtime": "edge", + "X-Stainless-Runtime-Version": globalThis.process.version + }; + } + if (detectedPlatform === "node") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION2, + "X-Stainless-OS": normalizePlatform2(globalThis.process.platform ?? "unknown"), + "X-Stainless-Arch": normalizeArch2(globalThis.process.arch ?? "unknown"), + "X-Stainless-Runtime": "node", + "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown" + }; + } + const browserInfo = getBrowserInfo2(); + if (browserInfo) { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION2, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": "unknown", + "X-Stainless-Runtime": `browser:${browserInfo.browser}`, + "X-Stainless-Runtime-Version": browserInfo.version + }; + } + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION2, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": "unknown", + "X-Stainless-Runtime": "unknown", + "X-Stainless-Runtime-Version": "unknown" + }; +}; +function getBrowserInfo2() { + if (typeof navigator === "undefined" || !navigator) { + return null; + } + const browserPatterns = [ + { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ } + ]; + for (const { key, pattern } of browserPatterns) { + const match = pattern.exec(navigator.userAgent); + if (match) { + const major = match[1] || 0; + const minor = match[2] || 0; + const patch = match[3] || 0; + return { browser: key, version: `${major}.${minor}.${patch}` }; + } + } + return null; +} +var normalizeArch2 = (arch) => { + if (arch === "x32") + return "x32"; + if (arch === "x86_64" || arch === "x64") + return "x64"; + if (arch === "arm") + return "arm"; + if (arch === "aarch64" || arch === "arm64") + return "arm64"; + if (arch) + return `other:${arch}`; + return "unknown"; +}; +var normalizePlatform2 = (platform) => { + platform = platform.toLowerCase(); + if (platform.includes("ios")) + return "iOS"; + if (platform === "android") + return "Android"; + if (platform === "darwin") + return "MacOS"; + if (platform === "win32") + return "Windows"; + if (platform === "freebsd") + return "FreeBSD"; + if (platform === "openbsd") + return "OpenBSD"; + if (platform === "linux") + return "Linux"; + if (platform) + return `Other:${platform}`; + return "Unknown"; +}; +var _platformHeaders2; +var getPlatformHeaders2 = () => { + return _platformHeaders2 ?? (_platformHeaders2 = getPlatformProperties2()); +}; + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/shims.mjs +function getDefaultFetch2() { + if (typeof fetch !== "undefined") { + return fetch; + } + throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new GitHub({ fetch })` or polyfill the global, `globalThis.fetch = fetch`"); +} +function makeReadableStream2(...args) { + const ReadableStream = globalThis.ReadableStream; + if (typeof ReadableStream === "undefined") { + throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`"); + } + return new ReadableStream(...args); +} +function ReadableStreamFrom2(iterable) { let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); return makeReadableStream2({ start() { @@ -14334,992 +12914,1668 @@ async function CancelReadableStream2(stream) { await cancelPromise; } -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/uploads.mjs -var checkFileSupport2 = () => { - if (typeof File === "undefined") { - const { process: process7 } = globalThis; - const isOldNode = typeof process7?.versions?.node === "string" && parseInt(process7.versions.node.split(".")) < 20; - throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : "")); - } +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/request-options.mjs +var FallbackEncoder2 = ({ headers, body }) => { + return { + bodyHeaders: { + "content-type": "application/json" + }, + body: JSON.stringify(body) + }; }; -function makeFile2(fileBits, fileName, options) { - checkFileSupport2(); - return new File(fileBits, fileName ?? "unknown_file", options); -} -function getName2(value) { - return (typeof value === "object" && value !== null && ("name" in value && value.name && String(value.name) || "url" in value && value.url && String(value.url) || "filename" in value && value.filename && String(value.filename) || "path" in value && value.path && String(value.path)) || "").split(/[\\/]/).pop() || void 0; -} -var isAsyncIterable2 = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function"; -var multipartFormRequestOptions = async (opts, fetch2) => { - return { ...opts, body: await createForm(opts.body, fetch2) }; + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/qs/formats.mjs +var default_format2 = "RFC3986"; +var default_formatter2 = (v) => String(v); +var formatters2 = { + RFC1738: (v) => String(v).replace(/%20/g, "+"), + RFC3986: default_formatter2 }; -var supportsFormDataMap = /* @__PURE__ */ new WeakMap(); -function supportsFormData(fetchObject) { - const fetch2 = typeof fetchObject === "function" ? fetchObject : fetchObject.fetch; - const cached = supportsFormDataMap.get(fetch2); - if (cached) - return cached; - const promise = (async () => { - try { - const FetchResponse = "Response" in fetch2 ? fetch2.Response : (await fetch2("data:,")).constructor; - const data = new FormData(); - if (data.toString() === await new FetchResponse(data).text()) { - return false; +var RFC17382 = "RFC1738"; + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/qs/utils.mjs +var has2 = (obj, key) => (has2 = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has2(obj, key)); +var hex_table2 = /* @__PURE__ */ (() => { + const array = []; + for (let i = 0; i < 256; ++i) { + array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase()); + } + return array; +})(); +var limit2 = 1024; +var encode2 = (str, _defaultEncoder, charset, _kind, format) => { + if (str.length === 0) { + return str; + } + let string = str; + if (typeof str === "symbol") { + string = Symbol.prototype.toString.call(str); + } else if (typeof str !== "string") { + string = String(str); + } + if (charset === "iso-8859-1") { + return escape(string).replace(/%u[0-9a-f]{4}/gi, function($0) { + return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; + }); + } + let out = ""; + for (let j = 0; j < string.length; j += limit2) { + const segment = string.length >= limit2 ? string.slice(j, j + limit2) : string; + const arr = []; + for (let i = 0; i < segment.length; ++i) { + let c = segment.charCodeAt(i); + if (c === 45 || // - + c === 46 || // . + c === 95 || // _ + c === 126 || // ~ + c >= 48 && c <= 57 || // 0-9 + c >= 65 && c <= 90 || // a-z + c >= 97 && c <= 122 || // A-Z + format === RFC17382 && (c === 40 || c === 41)) { + arr[arr.length] = segment.charAt(i); + continue; } - return true; - } catch { - return true; + if (c < 128) { + arr[arr.length] = hex_table2[c]; + continue; + } + if (c < 2048) { + arr[arr.length] = hex_table2[192 | c >> 6] + hex_table2[128 | c & 63]; + continue; + } + if (c < 55296 || c >= 57344) { + arr[arr.length] = hex_table2[224 | c >> 12] + hex_table2[128 | c >> 6 & 63] + hex_table2[128 | c & 63]; + continue; + } + i += 1; + c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023); + arr[arr.length] = hex_table2[240 | c >> 18] + hex_table2[128 | c >> 12 & 63] + hex_table2[128 | c >> 6 & 63] + hex_table2[128 | c & 63]; } - })(); - supportsFormDataMap.set(fetch2, promise); - return promise; -} -var createForm = async (body, fetch2) => { - if (!await supportsFormData(fetch2)) { - throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class."); + out += arr.join(""); } - const form = new FormData(); - await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value))); - return form; + return out; }; -var isNamedBlob = (value) => value instanceof Blob && "name" in value; -var addFormValue = async (form, key, value) => { - if (value === void 0) - return; - if (value == null) { - throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`); +function is_buffer2(obj) { + if (!obj || typeof obj !== "object") { + return false; } - if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { - form.append(key, String(value)); - } else if (value instanceof Response) { - form.append(key, makeFile2([await value.blob()], getName2(value))); - } else if (isAsyncIterable2(value)) { - form.append(key, makeFile2([await new Response(ReadableStreamFrom2(value)).blob()], getName2(value))); - } else if (isNamedBlob(value)) { - form.append(key, value, getName2(value)); - } else if (Array.isArray(value)) { - await Promise.all(value.map((entry) => addFormValue(form, key + "[]", entry))); - } else if (typeof value === "object") { - await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop))); - } else { - throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +} +function maybe_map2(val, fn) { + if (isArray2(val)) { + const mapped = []; + for (let i = 0; i < val.length; i += 1) { + mapped.push(fn(val[i])); + } + return mapped; } -}; + return fn(val); +} -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/resources/projects/repository/commits/commits.mjs -var BaseCommits3 = /* @__PURE__ */ (() => { - class BaseCommits4 extends APIResource2 { - /** - * This feature was introduced in GitLab 8.13 - * - * @example - * ```ts - * const apiEntitiesCommitDetail = - * await client.projects.repository.commits.create( - * 'string', - * { file: fs.createReadStream('path/to/file') }, - * ); - * ``` - */ - create(id, body, options) { - return this._client.post(path2`/projects/${id}/repository/commits`, multipartFormRequestOptions({ body, ...options }, this._client)); - } - /** - * Get a specific commit of a project - * - * @example - * ```ts - * const apiEntitiesCommitDetail = - * await client.projects.repository.commits.retrieve('sha', { - * id: 'string', - * }); - * ``` - */ - retrieve(sha, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/repository/commits/${sha}`, { query, ...options }); - } - /** - * Get a project repository commits - * - * @example - * ```ts - * const apiEntitiesCommits = - * await client.projects.repository.commits.list('string'); - * ``` - */ - list(id, query = {}, options) { - return this._client.get(path2`/projects/${id}/repository/commits`, { query, ...options }); +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/qs/stringify.mjs +var array_prefix_generators2 = { + brackets(prefix) { + return String(prefix) + "[]"; + }, + comma: "comma", + indices(prefix, key) { + return String(prefix) + "[" + key + "]"; + }, + repeat(prefix) { + return String(prefix); + } +}; +var push_to_array2 = function(arr, value_or_array) { + Array.prototype.push.apply(arr, isArray2(value_or_array) ? value_or_array : [value_or_array]); +}; +var toISOString2; +var defaults2 = { + addQueryPrefix: false, + allowDots: false, + allowEmptyArrays: false, + arrayFormat: "indices", + charset: "utf-8", + charsetSentinel: false, + delimiter: "&", + encode: true, + encodeDotInKeys: false, + encoder: encode2, + encodeValuesOnly: false, + format: default_format2, + formatter: default_formatter2, + /** @deprecated */ + indices: false, + serializeDate(date) { + return (toISOString2 ?? (toISOString2 = Function.prototype.call.bind(Date.prototype.toISOString)))(date); + }, + skipNulls: false, + strictNullHandling: false +}; +function is_non_nullish_primitive2(v) { + return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint"; +} +var sentinel2 = {}; +function inner_stringify2(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { + let obj = object; + let tmp_sc = sideChannel; + let step = 0; + let find_flag = false; + while ((tmp_sc = tmp_sc.get(sentinel2)) !== void 0 && !find_flag) { + const pos = tmp_sc.get(object); + step += 1; + if (typeof pos !== "undefined") { + if (pos === step) { + throw new RangeError("Cyclic object value"); + } else { + find_flag = true; + } } - /** - * Authorize commits upload - * - * @example - * ```ts - * await client.projects.repository.commits.authorize( - * 'string', - * ); - * ``` - */ - authorize(id, options) { - return this._client.post(path2`/projects/${id}/repository/commits/authorize`, { - ...options, - headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) - }); + if (typeof tmp_sc.get(sentinel2) === "undefined") { + step = 0; } - /** - * This feature was introduced in GitLab 8.15 - * - * @example - * ```ts - * const apiEntitiesCommit = - * await client.projects.repository.commits.cherryPick( - * 'sha', - * { id: 'string', branch: 'master' }, - * ); - * ``` - */ - cherryPick(sha, params, options) { - const { id, ...body } = params; - return this._client.post(path2`/projects/${id}/repository/commits/${sha}/cherry_pick`, { - body, - ...options - }); + } + if (typeof filter === "function") { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate?.(obj); + } else if (generateArrayPrefix === "comma" && isArray2(obj)) { + obj = maybe_map2(obj, function(value) { + if (value instanceof Date) { + return serializeDate?.(value); + } + return value; + }); + } + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? ( + // @ts-expect-error + encoder(prefix, defaults2.encoder, charset, "key", format) + ) : prefix; } - /** - * Get the diff for a specific commit of a project - * - * @example - * ```ts - * const apiEntitiesDiffs = - * await client.projects.repository.commits.retrieveDiff( - * 'sha', - * { id: 'string' }, - * ); - * ``` - */ - retrieveDiff(sha, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/repository/commits/${sha}/diff`, { query, ...options }); + obj = ""; + } + if (is_non_nullish_primitive2(obj) || is_buffer2(obj)) { + if (encoder) { + const key_value = encodeValuesOnly ? prefix : encoder(prefix, defaults2.encoder, charset, "key", format); + return [ + formatter?.(key_value) + "=" + // @ts-expect-error + formatter?.(encoder(obj, defaults2.encoder, charset, "value", format)) + ]; } - /** - * Get Merge Requests associated with a commit - * - * @example - * ```ts - * const apiEntitiesMergeRequestBasic = - * await client.projects.repository.commits.retrieveMergeRequests( - * 'sha', - * { id: 'string' }, - * ); - * ``` - */ - retrieveMergeRequests(sha, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/repository/commits/${sha}/merge_requests`, { - query, - ...options - }); + return [formatter?.(prefix) + "=" + formatter?.(String(obj))]; + } + const values = []; + if (typeof obj === "undefined") { + return values; + } + let obj_keys; + if (generateArrayPrefix === "comma" && isArray2(obj)) { + if (encodeValuesOnly && encoder) { + obj = maybe_map2(obj, encoder); } - /** - * This feature was introduced in GitLab 10.6 - * - * @example - * ```ts - * const response = - * await client.projects.repository.commits.retrieveRefs( - * 'sha', - * { id: 'string' }, - * ); - * ``` - */ - retrieveRefs(sha, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/repository/commits/${sha}/refs`, { query, ...options }); + obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; + } else if (isArray2(filter)) { + obj_keys = filter; + } else { + const keys = Object.keys(obj); + obj_keys = sort ? keys.sort(sort) : keys; + } + const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix); + const adjusted_prefix = commaRoundTrip && isArray2(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix; + if (allowEmptyArrays && isArray2(obj) && obj.length === 0) { + return adjusted_prefix + "[]"; + } + for (let j = 0; j < obj_keys.length; ++j) { + const key = obj_keys[j]; + const value = ( + // @ts-ignore + typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key] + ); + if (skipNulls && value === null) { + continue; } - /** - * Get the sequence count of a commit SHA - * - * @example - * ```ts - * const response = - * await client.projects.repository.commits.retrieveSequence( - * 'sha', - * { id: 'string' }, - * ); + const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key; + const key_prefix = isArray2(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]"); + sideChannel.set(object, step); + const valueSideChannel = /* @__PURE__ */ new WeakMap(); + valueSideChannel.set(sentinel2, sideChannel); + push_to_array2(values, inner_stringify2( + value, + key_prefix, + generateArrayPrefix, + commaRoundTrip, + allowEmptyArrays, + strictNullHandling, + skipNulls, + encodeDotInKeys, + // @ts-ignore + generateArrayPrefix === "comma" && encodeValuesOnly && isArray2(obj) ? null : encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + valueSideChannel + )); + } + return values; +} +function normalize_stringify_options2(opts = defaults2) { + if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") { + throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); + } + if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") { + throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided"); + } + if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") { + throw new TypeError("Encoder has to be a function."); + } + const charset = opts.charset || defaults2.charset; + if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { + throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); + } + let format = default_format2; + if (typeof opts.format !== "undefined") { + if (!has2(formatters2, opts.format)) { + throw new TypeError("Unknown format option provided."); + } + format = opts.format; + } + const formatter = formatters2[format]; + let filter = defaults2.filter; + if (typeof opts.filter === "function" || isArray2(opts.filter)) { + filter = opts.filter; + } + let arrayFormat; + if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators2) { + arrayFormat = opts.arrayFormat; + } else if ("indices" in opts) { + arrayFormat = opts.indices ? "indices" : "repeat"; + } else { + arrayFormat = defaults2.arrayFormat; + } + if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") { + throw new TypeError("`commaRoundTrip` must be a boolean, or absent"); + } + const allowDots = typeof opts.allowDots === "undefined" ? !!opts.encodeDotInKeys === true ? true : defaults2.allowDots : !!opts.allowDots; + return { + addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults2.addQueryPrefix, + // @ts-ignore + allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults2.allowEmptyArrays, + arrayFormat, + charset, + charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults2.charsetSentinel, + commaRoundTrip: !!opts.commaRoundTrip, + delimiter: typeof opts.delimiter === "undefined" ? defaults2.delimiter : opts.delimiter, + encode: typeof opts.encode === "boolean" ? opts.encode : defaults2.encode, + encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults2.encodeDotInKeys, + encoder: typeof opts.encoder === "function" ? opts.encoder : defaults2.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults2.encodeValuesOnly, + filter, + format, + formatter, + serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults2.serializeDate, + skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults2.skipNulls, + // @ts-ignore + sort: typeof opts.sort === "function" ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults2.strictNullHandling + }; +} +function stringify2(object, opts = {}) { + let obj = object; + const options = normalize_stringify_options2(opts); + let obj_keys; + let filter; + if (typeof options.filter === "function") { + filter = options.filter; + obj = filter("", obj); + } else if (isArray2(options.filter)) { + filter = options.filter; + obj_keys = filter; + } + const keys = []; + if (typeof obj !== "object" || obj === null) { + return ""; + } + const generateArrayPrefix = array_prefix_generators2[options.arrayFormat]; + const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip; + if (!obj_keys) { + obj_keys = Object.keys(obj); + } + if (options.sort) { + obj_keys.sort(options.sort); + } + const sideChannel = /* @__PURE__ */ new WeakMap(); + for (let i = 0; i < obj_keys.length; ++i) { + const key = obj_keys[i]; + if (options.skipNulls && obj[key] === null) { + continue; + } + push_to_array2(keys, inner_stringify2( + obj[key], + key, + // @ts-expect-error + generateArrayPrefix, + commaRoundTrip, + options.allowEmptyArrays, + options.strictNullHandling, + options.skipNulls, + options.encodeDotInKeys, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.format, + options.formatter, + options.encodeValuesOnly, + options.charset, + sideChannel + )); + } + const joined = keys.join(options.delimiter); + let prefix = options.addQueryPrefix === true ? "?" : ""; + if (options.charsetSentinel) { + if (options.charset === "iso-8859-1") { + prefix += "utf8=%26%2310003%3B&"; + } else { + prefix += "utf8=%E2%9C%93&"; + } + } + return joined.length > 0 ? prefix + joined : ""; +} + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/resources/apps/installations/installations.mjs +var BaseInstallations = /* @__PURE__ */ (() => { + class BaseInstallations4 extends APIResource2 { + /** + * Enables an authenticated GitHub App to find an installation's information using + * the installation id. + * + * You must use a + * [JWT](https://docs.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) + * to access this endpoint. + * + * @example + * ```ts + * const installation = + * await client.apps.installations.retrieve(0); * ``` */ - retrieveSequence(sha, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/repository/commits/${sha}/sequence`, { query, ...options }); + retrieve(installationID, options) { + return this._client.get(path2`/app/installations/${installationID}`, options); } /** - * Get a commit's signature + * The permissions the installation has are included under the `permissions` key. + * + * You must use a + * [JWT](https://docs.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) + * to access this endpoint. * * @example * ```ts - * const response = - * await client.projects.repository.commits.retrieveSignature( - * 'sha', - * { id: 'string' }, - * ); + * // Automatically fetches more pages as needed. + * for await (const installation of client.apps.installations.list()) { + * // ... + * } * ``` */ - retrieveSignature(sha, params, options) { - const { id } = params; - return this._client.get(path2`/projects/${id}/repository/commits/${sha}/signature`, options); + list(query = {}, options) { + return this._client.getAPIList("/app/installations", NumberedPage, { + query, + ...options + }); } /** - * Get a commit's statuses + * Uninstalls a GitHub App on a user, organization, or enterprise account. If you + * prefer to temporarily suspend an app's access to your account's resources, then + * we recommend the + * "[Suspend an app installation](https://docs.github.com/rest/apps/apps#suspend-an-app-installation)" + * endpoint. + * + * You must use a + * [JWT](https://docs.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) + * to access this endpoint. * * @example * ```ts - * const apiEntitiesCommitStatus = - * await client.projects.repository.commits.retrieveStatuses( - * '18f3e63d05582537db6d183d9d557be09e1f90c8', - * { id: 'string' }, - * ); + * await client.apps.installations.delete(0); * ``` */ - retrieveStatuses(sha, params, options) { - const { id, ...query } = params; - return this._client.get(path2`/projects/${id}/repository/commits/${sha}/statuses`, { query, ...options }); + delete(installationID, options) { + return this._client.delete(path2`/app/installations/${installationID}`, { + ...options, + headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + }); } /** - * This feature was introduced in GitLab 11.5 + * Creates an installation access token that enables a GitHub App to make + * authenticated API requests for the app's installation on an organization or + * individual account. Installation tokens expire one hour from the time you create + * them. Using an expired token produces a status code of `401 - Unauthorized`, and + * requires creating a new installation token. By default the installation token + * has access to all repositories that the installation can access. + * + * Optionally, you can use the `repositories` or `repository_ids` body parameters + * to specify individual repositories that the installation access token can + * access. If you don't use `repositories` or `repository_ids` to grant access to + * specific repositories, the installation access token will have access to all + * repositories that the installation was granted access to. The installation + * access token cannot be granted access to repositories that the installation was + * not granted access to. Up to 500 repositories can be listed in this manner. + * + * Optionally, use the `permissions` body parameter to specify the permissions that + * the installation access token should have. If `permissions` is not specified, + * the installation access token will have all of the permissions that were granted + * to the app. The installation access token cannot be granted permissions that the + * app was not granted. + * + * You must use a + * [JWT](https://docs.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) + * to access this endpoint. * * @example * ```ts - * const apiEntitiesCommit = - * await client.projects.repository.commits.revert('sha', { - * id: 'string', - * branch: 'master', + * const response = + * await client.apps.installations.createAccessToken(0, { + * permissions: { issues: 'write', contents: 'read' }, + * repositories: ['Hello-World'], * }); * ``` */ - revert(sha, params, options) { - const { id, ...body } = params; - return this._client.post(path2`/projects/${id}/repository/commits/${sha}/revert`, { body, ...options }); + createAccessToken(installationID, body = {}, options) { + return this._client.post(path2`/app/installations/${installationID}/access_tokens`, { body, ...options }); } } - BaseCommits4._key = Object.freeze([ - "projects", - "repository", - "commits" + BaseInstallations4._key = Object.freeze([ + "apps", + "installations" ]); - return BaseCommits4; + return BaseInstallations4; })(); -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/tslib.mjs -function __classPrivateFieldSet2(receiver, state, value, kind, f) { - if (kind === "m") - throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) - throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) - throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; -} -function __classPrivateFieldGet2(receiver, state, kind, f) { - if (kind === "a" && !f) - throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) - throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -} - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/utils/uuid.mjs -var uuid42 = function() { - const { crypto: crypto2 } = globalThis; - if (crypto2?.randomUUID) { - uuid42 = crypto2.randomUUID.bind(crypto2); - return crypto2.randomUUID(); - } - const u8 = new Uint8Array(1); - const randomByte = crypto2 ? () => crypto2.getRandomValues(u8)[0] : () => Math.random() * 255 & 255; - return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16)); -}; - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/utils/sleep.mjs -var sleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/version.mjs -var VERSION2 = "0.3.0"; - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/detect-platform.mjs -function getDetectedPlatform2() { - if (typeof Deno !== "undefined" && Deno.build != null) { - return "deno"; - } - if (typeof EdgeRuntime !== "undefined") { - return "edge"; - } - if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") { - return "node"; - } - return "unknown"; -} -var getPlatformProperties2 = () => { - const detectedPlatform = getDetectedPlatform2(); - if (detectedPlatform === "deno") { - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION2, - "X-Stainless-OS": normalizePlatform2(Deno.build.os), - "X-Stainless-Arch": normalizeArch2(Deno.build.arch), - "X-Stainless-Runtime": "deno", - "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown" - }; - } - if (typeof EdgeRuntime !== "undefined") { - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION2, - "X-Stainless-OS": "Unknown", - "X-Stainless-Arch": `other:${EdgeRuntime}`, - "X-Stainless-Runtime": "edge", - "X-Stainless-Runtime-Version": globalThis.process.version - }; - } - if (detectedPlatform === "node") { - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION2, - "X-Stainless-OS": normalizePlatform2(globalThis.process.platform ?? "unknown"), - "X-Stainless-Arch": normalizeArch2(globalThis.process.arch ?? "unknown"), - "X-Stainless-Runtime": "node", - "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown" - }; - } - const browserInfo = getBrowserInfo2(); - if (browserInfo) { - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION2, - "X-Stainless-OS": "Unknown", - "X-Stainless-Arch": "unknown", - "X-Stainless-Runtime": `browser:${browserInfo.browser}`, - "X-Stainless-Runtime-Version": browserInfo.version - }; - } - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION2, - "X-Stainless-OS": "Unknown", - "X-Stainless-Arch": "unknown", - "X-Stainless-Runtime": "unknown", - "X-Stainless-Runtime-Version": "unknown" - }; -}; -function getBrowserInfo2() { - if (typeof navigator === "undefined" || !navigator) { - return null; - } - const browserPatterns = [ - { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ } - ]; - for (const { key, pattern } of browserPatterns) { - const match = pattern.exec(navigator.userAgent); - if (match) { - const major = match[1] || 0; - const minor = match[2] || 0; - const patch = match[3] || 0; - return { browser: key, version: `${major}.${minor}.${patch}` }; +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/resources/orgs/orgs.mjs +var BaseOrgs = /* @__PURE__ */ (() => { + class BaseOrgs3 extends APIResource2 { + /** + * Gets information about an organization. + * + * When the value of `two_factor_requirement_enabled` is `true`, the organization + * requires all members, billing managers, outside collaborators, guest + * collaborators, repository collaborators, or everyone with access to any + * repository within the organization to enable + * [two-factor authentication](https://docs.github.com/articles/securing-your-account-with-two-factor-authentication-2fa/). + * + * To see the full details about an organization, the authenticated user must be an + * organization owner. + * + * OAuth app tokens and personal access tokens (classic) need the `admin:org` scope + * to see the full details about an organization. + * + * To see information about an organization's GitHub plan, GitHub Apps need the + * `Organization plan` permission. + * + * @example + * ```ts + * const org = await client.orgs.retrieve('org'); + * ``` + */ + retrieve(org, options) { + return this._client.get(path2`/orgs/${org}`, options); } - } - return null; -} -var normalizeArch2 = (arch) => { - if (arch === "x32") - return "x32"; - if (arch === "x86_64" || arch === "x64") - return "x64"; - if (arch === "arm") - return "arm"; - if (arch === "aarch64" || arch === "arm64") - return "arm64"; - if (arch) - return `other:${arch}`; - return "unknown"; -}; -var normalizePlatform2 = (platform) => { - platform = platform.toLowerCase(); - if (platform.includes("ios")) - return "iOS"; - if (platform === "android") - return "Android"; - if (platform === "darwin") - return "MacOS"; - if (platform === "win32") - return "Windows"; - if (platform === "freebsd") - return "FreeBSD"; - if (platform === "openbsd") - return "OpenBSD"; - if (platform === "linux") - return "Linux"; - if (platform) - return `Other:${platform}`; - return "Unknown"; -}; -var _platformHeaders2; -var getPlatformHeaders2 = () => { - return _platformHeaders2 ?? (_platformHeaders2 = getPlatformProperties2()); -}; - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/request-options.mjs -var FallbackEncoder2 = ({ headers, body }) => { - return { - bodyHeaders: { - "content-type": "application/json" - }, - body: JSON.stringify(body) - }; -}; - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/qs/formats.mjs -var default_format2 = "RFC3986"; -var default_formatter2 = (v) => String(v); -var formatters2 = { - RFC1738: (v) => String(v).replace(/%20/g, "+"), - RFC3986: default_formatter2 -}; -var RFC17382 = "RFC1738"; - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/qs/utils.mjs -var has2 = (obj, key) => (has2 = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has2(obj, key)); -var hex_table2 = /* @__PURE__ */ (() => { - const array = []; - for (let i = 0; i < 256; ++i) { - array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase()); - } - return array; -})(); -var limit2 = 1024; -var encode2 = (str, _defaultEncoder, charset, _kind, format) => { - if (str.length === 0) { - return str; - } - let string = str; - if (typeof str === "symbol") { - string = Symbol.prototype.toString.call(str); - } else if (typeof str !== "string") { - string = String(str); - } - if (charset === "iso-8859-1") { - return escape(string).replace(/%u[0-9a-f]{4}/gi, function($0) { - return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; - }); - } - let out = ""; - for (let j = 0; j < string.length; j += limit2) { - const segment = string.length >= limit2 ? string.slice(j, j + limit2) : string; - const arr = []; - for (let i = 0; i < segment.length; ++i) { - let c = segment.charCodeAt(i); - if (c === 45 || // - - c === 46 || // . - c === 95 || // _ - c === 126 || // ~ - c >= 48 && c <= 57 || // 0-9 - c >= 65 && c <= 90 || // a-z - c >= 97 && c <= 122 || // A-Z - format === RFC17382 && (c === 40 || c === 41)) { - arr[arr.length] = segment.charAt(i); - continue; - } - if (c < 128) { - arr[arr.length] = hex_table2[c]; - continue; - } - if (c < 2048) { - arr[arr.length] = hex_table2[192 | c >> 6] + hex_table2[128 | c & 63]; - continue; - } - if (c < 55296 || c >= 57344) { - arr[arr.length] = hex_table2[224 | c >> 12] + hex_table2[128 | c >> 6 & 63] + hex_table2[128 | c & 63]; - continue; - } - i += 1; - c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023); - arr[arr.length] = hex_table2[240 | c >> 18] + hex_table2[128 | c >> 12 & 63] + hex_table2[128 | c >> 6 & 63] + hex_table2[128 | c & 63]; + /** + * > [!WARNING] > **Closing down notice:** GitHub will replace and discontinue + * > `members_allowed_repository_creation_type` in favor of more granular + * > permissions. The new input parameters are + * > `members_can_create_public_repositories`, + * > `members_can_create_private_repositories` for all organizations and + * > `members_can_create_internal_repositories` for organizations associated with + * > an enterprise account using GitHub Enterprise Cloud or GitHub Enterprise + * > Server 2.20+. For more information, see the + * > [blog post](https://developer.github.com/changes/2019-12-03-internal-visibility-changes). + * + * > [!WARNING] > **Closing down notice:** Code security product enablement for new + * > repositories through the organization API is closing down. Please use + * > [code security configurations](https://docs.github.com/rest/code-security/configurations#set-a-code-security-configuration-as-a-default-for-an-organization) + * > to set defaults instead. For more information on setting a default security + * > configuration, see the + * > [changelog](https://github.blog/changelog/2024-07-09-sunsetting-security-settings-defaults-parameters-in-the-organizations-rest-api/). + * + * Updates the organization's profile and member privileges. + * + * The authenticated user must be an organization owner to use this endpoint. + * + * OAuth app tokens and personal access tokens (classic) need the `admin:org` or + * `repo` scope to use this endpoint. + * + * @example + * ```ts + * const org = await client.orgs.update('org', { + * billing_email: 'mona@github.com', + * company: 'GitHub', + * default_repository_permission: 'read', + * description: 'GitHub, the company.', + * email: 'mona@github.com', + * location: 'San Francisco', + * members_allowed_repository_creation_type: 'all', + * members_can_create_repositories: true, + * name: 'github', + * twitter_username: 'github', + * }); + * ``` + */ + update(org, body = {}, options) { + return this._client.patch(path2`/orgs/${org}`, { body, ...options }); + } + /** + * Deletes an organization and all its repositories. + * + * The organization login will be unavailable for 90 days after deletion. + * + * Please review the Terms of Service regarding account deletion before using this + * endpoint: + * + * https://docs.github.com/site-policy/github-terms/github-terms-of-service + * + * @example + * ```ts + * const org = await client.orgs.delete('org'); + * ``` + */ + delete(org, options) { + return this._client.delete(path2`/orgs/${org}`, options); + } + /** + * List a collection of artifact attestations with a given subject digest that are + * associated with repositories owned by an organization. + * + * The collection of attestations returned by this endpoint is filtered according + * to the authenticated user's permissions; if the authenticated user cannot read a + * repository, the attestations associated with that repository will not be + * included in the response. In addition, when using a fine-grained access token + * the `attestations:read` permission is required. + * + * **Please note:** in order to offer meaningful security benefits, an + * attestation's signature and timestamps **must** be cryptographically verified, + * and the identity of the attestation signer **must** be validated. Attestations + * can be verified using the + * [GitHub CLI `attestation verify` command](https://cli.github.com/manual/gh_attestation_verify). + * For more information, see + * [our guide on how to use artifact attestations to establish a build's provenance](https://docs.github.com/actions/security-guides/using-artifact-attestations-to-establish-provenance-for-builds). + * + * @example + * ```ts + * const response = await client.orgs.listAttestations( + * 'subject_digest', + * { org: 'org' }, + * ); + * ``` + */ + listAttestations(subjectDigest, params, options) { + const { org, ...query } = params; + return this._client.get(path2`/orgs/${org}/attestations/${subjectDigest}`, { query, ...options }); + } + /** + * > [!NOTE] This API is not built to serve real-time use cases. Depending on the + * > time of day, event latency can be anywhere from 30s to 6h. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const orgListEventsResponse of client.orgs.listEvents( + * 'org', + * )) { + * // ... + * } + * ``` + */ + listEvents(org, query = {}, options) { + return this._client.getAPIList(path2`/orgs/${org}/events`, NumberedPage, { + query, + ...options + }); + } + /** + * The return hash contains `failed_at` and `failed_reason` fields which represent + * the time at which the invitation failed and the reason for the failure. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const orgListFailedInvitationsResponse of client.orgs.listFailedInvitations( + * 'org', + * )) { + * // ... + * } + * ``` + */ + listFailedInvitations(org, query = {}, options) { + return this._client.getAPIList(path2`/orgs/${org}/failed_invitations`, NumberedPage, { query, ...options }); + } + /** + * Lists all GitHub Apps in an organization. The installation count includes all + * GitHub Apps installed on repositories in the organization. + * + * The authenticated user must be an organization owner to use this endpoint. + * + * OAuth app tokens and personal access tokens (classic) need the `admin:read` + * scope to use this endpoint. + * + * @example + * ```ts + * const response = await client.orgs.listInstallations('org'); + * ``` + */ + listInstallations(org, query = {}, options) { + return this._client.get(path2`/orgs/${org}/installations`, { query, ...options }); + } + /** + * List issues in an organization assigned to the authenticated user. + * + * > [!NOTE] GitHub's REST API considers every pull request an issue, but not every + * > issue is a pull request. For this reason, "Issues" endpoints may return both + * > issues and pull requests in the response. You can identify pull requests by + * > the `pull_request` key. Be aware that the `id` of a pull request returned from + * > "Issues" endpoints will be an _issue id_. To find out the pull request id, use + * > the + * > "[List pull requests](https://docs.github.com/rest/pulls/pulls#list-pull-requests)" + * > endpoint. + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.raw+json`**: Returns the raw markdown body. Response + * will include `body`. This is the default if you do not pass any specific media + * type. + * - **`application/vnd.github.text+json`**: Returns a text only representation of + * the markdown body. Response will include `body_text`. + * - **`application/vnd.github.html+json`**: Returns HTML rendered from the body's + * markdown. Response will include `body_html`. + * - **`application/vnd.github.full+json`**: Returns raw, text, and HTML + * representations. Response will include `body`, `body_text`, and `body_html`. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const issue of client.orgs.listIssues('org')) { + * // ... + * } + * ``` + */ + listIssues(org, query = {}, options) { + return this._client.getAPIList(path2`/orgs/${org}/issues`, NumberedPage, { + query, + ...options + }); + } + /** + * Lists repository security advisories for an organization. + * + * The authenticated user must be an owner or security manager for the organization + * to use this endpoint. + * + * OAuth app tokens and personal access tokens (classic) need the `repo` or + * `repository_advisories:write` scope to use this endpoint. + * + * @example + * ```ts + * const response = await client.orgs.listSecurityAdvisories( + * 'org', + * ); + * ``` + */ + listSecurityAdvisories(org, query = {}, options) { + return this._client.get(path2`/orgs/${org}/security-advisories`, { query, ...options }); + } + /** + * Enables an authenticated GitHub App to find the organization's installation + * information. + * + * You must use a + * [JWT](https://docs.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) + * to access this endpoint. + * + * @example + * ```ts + * const installation = await client.orgs.retrieveInstallation( + * 'org', + * ); + * ``` + */ + retrieveInstallation(org, options) { + return this._client.get(path2`/orgs/${org}/installation`, options); + } + } + BaseOrgs3._key = Object.freeze(["orgs"]); + return BaseOrgs3; +})(); + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/resources/search.mjs +var BaseSearch = /* @__PURE__ */ (() => { + class BaseSearch6 extends APIResource2 { + /** + * Searches for query terms inside of a file. This method returns up to 100 results + * [per page](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api). + * + * When searching for code, you can get text match metadata for the file + * **content** and file **path** fields when you pass the `text-match` media type. + * For more details about how to receive highlighted search results, see + * [Text match metadata](https://docs.github.com/rest/search/search#text-match-metadata). + * + * For example, if you want to find the definition of the `addClass` function + * inside [jQuery](https://github.com/jquery/jquery) repository, your query would + * look something like this: + * + * `q=addClass+in:file+language:js+repo:jquery/jquery` + * + * This query searches for the keyword `addClass` within a file's contents. The + * query limits the search to files where the language is JavaScript in the + * `jquery/jquery` repository. + * + * Considerations for code search: + * + * Due to the complexity of searching code, there are a few restrictions on how + * searches are performed: + * + * - Only the _default branch_ is considered. In most cases, this will be the + * `master` branch. + * - Only files smaller than 384 KB are searchable. + * - You must always include at least one search term when searching source code. + * For example, searching for + * [`language:go`](https://github.com/search?utf8=%E2%9C%93&q=language%3Ago&type=Code) + * is not valid, while + * [`amazing language:go`](https://github.com/search?utf8=%E2%9C%93&q=amazing+language%3Ago&type=Code) + * is. + * + * This endpoint requires you to authenticate and limits you to 10 requests per + * minute. + */ + codeSearch(query, options) { + return this._client.get("/search/code", { query, ...options }); + } + /** + * Find commits via various criteria on the default branch (usually `main`). This + * method returns up to 100 results + * [per page](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api). + * + * When searching for commits, you can get text match metadata for the **message** + * field when you provide the `text-match` media type. For more details about how + * to receive highlighted search results, see + * [Text match metadata](https://docs.github.com/rest/search/search#text-match-metadata). + * + * For example, if you want to find commits related to CSS in the + * [octocat/Spoon-Knife](https://github.com/octocat/Spoon-Knife) repository. Your + * query would look something like this: + * + * `q=repo:octocat/Spoon-Knife+css` + */ + commitSearch(query, options) { + return this._client.get("/search/commits", { query, ...options }); + } + /** + * > [!WARNING] > **Notice:** Search for issues and pull requests will be + * > overridden by advanced search on November 4, 2025. You can read more about + * > this change on + * > [the GitHub blog](https://github.blog/changelog/2025-03-06-github-issues-projects-api-support-for-issues-advanced-search-and-more/). + * + * @deprecated + */ + issueSearch(query, options) { + return this._client.get("/search/issues", { query, ...options }); + } + /** + * Find labels in a repository with names or descriptions that match search + * keywords. Returns up to 100 results + * [per page](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api). + * + * When searching for labels, you can get text match metadata for the label + * **name** and **description** fields when you pass the `text-match` media type. + * For more details about how to receive highlighted search results, see + * [Text match metadata](https://docs.github.com/rest/search/search#text-match-metadata). + * + * For example, if you want to find labels in the `linguist` repository that match + * `bug`, `defect`, or `enhancement`. Your query might look like this: + * + * `q=bug+defect+enhancement&repository_id=64778136` + * + * The labels that best match the query appear first in the search results. + */ + labelSearch(query, options) { + return this._client.get("/search/labels", { query, ...options }); + } + /** + * Find repositories via various criteria. This method returns up to 100 results + * [per page](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api). + * + * When searching for repositories, you can get text match metadata for the + * **name** and **description** fields when you pass the `text-match` media type. + * For more details about how to receive highlighted search results, see + * [Text match metadata](https://docs.github.com/rest/search/search#text-match-metadata). + * + * For example, if you want to search for popular Tetris repositories written in + * assembly code, your query might look like this: + * + * `q=tetris+language:assembly&sort=stars&order=desc` + * + * This query searches for repositories with the word `tetris` in the name, the + * description, or the README. The results are limited to repositories where the + * primary language is assembly. The results are sorted by stars in descending + * order, so that the most popular repositories appear first in the search results. + */ + repositorySearch(query, options) { + return this._client.get("/search/repositories", { query, ...options }); + } + /** + * Find topics via various criteria. Results are sorted by best match. This method + * returns up to 100 results + * [per page](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api). + * See "[Searching topics](https://docs.github.com/articles/searching-topics/)" for + * a detailed list of qualifiers. + * + * When searching for topics, you can get text match metadata for the topic's + * **short_description**, **description**, **name**, or **display_name** field when + * you pass the `text-match` media type. For more details about how to receive + * highlighted search results, see + * [Text match metadata](https://docs.github.com/rest/search/search#text-match-metadata). + * + * For example, if you want to search for topics related to Ruby that are featured + * on https://github.com/topics. Your query might look like this: + * + * `q=ruby+is:featured` + * + * This query searches for topics with the keyword `ruby` and limits the results to + * find only topics that are featured. The topics that are the best match for the + * query appear first in the search results. + */ + topicSearch(query, options) { + return this._client.get("/search/topics", { query, ...options }); + } + /** + * Find users via various criteria. This method returns up to 100 results + * [per page](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api). + * + * When searching for users, you can get text match metadata for the issue + * **login**, public **email**, and **name** fields when you pass the `text-match` + * media type. For more details about highlighting search results, see + * [Text match metadata](https://docs.github.com/rest/search/search#text-match-metadata). + * For more details about how to receive highlighted search results, see + * [Text match metadata](https://docs.github.com/rest/search/search#text-match-metadata). + * + * For example, if you're looking for a list of popular users, you might try this + * query: + * + * `q=tom+repos:%3E42+followers:%3E1000` + * + * This query searches for users with the name `tom`. The results are restricted to + * users with more than 42 repositories and over 1,000 followers. + * + * This endpoint does not accept authentication and will only include publicly + * visible users. As an alternative, you can use the GraphQL API. The GraphQL API + * requires authentication and will return private users, including Enterprise + * Managed Users (EMUs), that you are authorized to view. For more information, see + * "[GraphQL Queries](https://docs.github.com/graphql/reference/queries#search)." + */ + userSearch(query, options) { + return this._client.get("/search/users", { query, ...options }); } - out += arr.join(""); } - return out; + BaseSearch6._key = Object.freeze(["search"]); + return BaseSearch6; +})(); +var Search = class extends BaseSearch { }; -function is_buffer2(obj) { - if (!obj || typeof obj !== "object") { - return false; - } - return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); -} -function maybe_map2(val, fn) { - if (isArray2(val)) { - const mapped = []; - for (let i = 0; i < val.length; i += 1) { - mapped.push(fn(val[i])); - } - return mapped; - } - return fn(val); -} -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/qs/stringify.mjs -var array_prefix_generators2 = { - brackets(prefix) { - return String(prefix) + "[]"; - }, - comma: "comma", - indices(prefix, key) { - return String(prefix) + "[" + key + "]"; - }, - repeat(prefix) { - return String(prefix); - } -}; -var push_to_array2 = function(arr, value_or_array) { - Array.prototype.push.apply(arr, isArray2(value_or_array) ? value_or_array : [value_or_array]); -}; -var toISOString2; -var defaults2 = { - addQueryPrefix: false, - allowDots: false, - allowEmptyArrays: false, - arrayFormat: "indices", - charset: "utf-8", - charsetSentinel: false, - delimiter: "&", - encode: true, - encodeDotInKeys: false, - encoder: encode2, - encodeValuesOnly: false, - format: default_format2, - formatter: default_formatter2, - /** @deprecated */ - indices: false, - serializeDate(date) { - return (toISOString2 ?? (toISOString2 = Function.prototype.call.bind(Date.prototype.toISOString)))(date); - }, - skipNulls: false, - strictNullHandling: false -}; -function is_non_nullish_primitive2(v) { - return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint"; -} -var sentinel2 = {}; -function inner_stringify2(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { - let obj = object; - let tmp_sc = sideChannel; - let step = 0; - let find_flag = false; - while ((tmp_sc = tmp_sc.get(sentinel2)) !== void 0 && !find_flag) { - const pos = tmp_sc.get(object); - step += 1; - if (typeof pos !== "undefined") { - if (pos === step) { - throw new RangeError("Cyclic object value"); - } else { - find_flag = true; - } +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/lib/secrets.mjs +var import_libsodium_wrappers = __toESM(require_libsodium_wrappers(), 1); + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/resources/repos/repos.mjs +var BaseRepos3 = /* @__PURE__ */ (() => { + class BaseRepos6 extends APIResource2 { + constructor() { + super(...arguments); + this._client_search = new Search(this._client); + this.search = { + codeSearch: (params, options) => { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params; + query.q = `repo:${owner}/${repo} ${query.q}`; + return this._client_search.codeSearch(query, options); + }, + commitSearch: (params, options) => { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params; + query.q = `repo:${owner}/${repo} ${query.q}`; + return this._client_search.commitSearch(query, options); + }, + issueSearch: (params, options) => { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params; + query.q = `repo:${owner}/${repo} ${query.q}`; + return this._client_search.issueSearch(query, options); + }, + labelSearch: (params, options) => { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params; + query.q = `repo:${owner}/${repo} ${query.q}`; + return this._client_search.labelSearch(query, options); + } + }; } - if (typeof tmp_sc.get(sentinel2) === "undefined") { - step = 0; + /** + * Creates a new repository for the authenticated user. + * + * OAuth app tokens and personal access tokens (classic) need the `public_repo` or + * `repo` scope to create a public repository, and `repo` scope to create a private + * repository. + * + * @example + * ```ts + * const fullRepository = await client.repos.create({ + * name: 'Hello-World', + * description: 'This is your first repo!', + * homepage: 'https://github.com', + * is_template: true, + * }); + * ``` + */ + create(body, options) { + return this._client.post("/user/repos", { body, ...options }); } - } - if (typeof filter === "function") { - obj = filter(prefix, obj); - } else if (obj instanceof Date) { - obj = serializeDate?.(obj); - } else if (generateArrayPrefix === "comma" && isArray2(obj)) { - obj = maybe_map2(obj, function(value) { - if (value instanceof Date) { - return serializeDate?.(value); - } - return value; - }); - } - if (obj === null) { - if (strictNullHandling) { - return encoder && !encodeValuesOnly ? ( - // @ts-expect-error - encoder(prefix, defaults2.encoder, charset, "key", format) - ) : prefix; + /** + * The `parent` and `source` objects are present when the repository is a fork. + * `parent` is the repository this repository was forked from, `source` is the + * ultimate source for the network. + * + * > [!NOTE] + * > + * > - In order to see the `security_and_analysis` block for a repository you must + * > have admin permissions for the repository or be an owner or security manager + * > for the organization that owns the repository. For more information, see + * > "[Managing security managers in your organization](https://docs.github.com/organizations/managing-peoples-access-to-your-organization-with-roles/managing-security-managers-in-your-organization)." + * > - To view merge-related settings, you must have the `contents:read` and + * > `contents:write` permissions. + * + * @example + * ```ts + * const fullRepository = await client.repos.retrieve({ + * owner: 'owner', + * repo: 'repo', + * }); + * ``` + */ + retrieve(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}`, options); + } + /** + * **Note**: To edit a repository's topics, use the + * [Replace all repository topics](https://docs.github.com/rest/repos/repos#replace-all-repository-topics) + * endpoint. + * + * @example + * ```ts + * const fullRepository = await client.repos.update({ + * owner: 'owner', + * repo: 'repo', + * description: 'This is your first repository', + * has_issues: true, + * has_projects: true, + * has_wiki: true, + * homepage: 'https://github.com', + * name: 'Hello-World', + * private: true, + * }); + * ``` + */ + update(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...body } = params ?? {}; + return this._client.patch(path2`/repos/${owner}/${repo}`, { body, ...options }); + } + /** + * Deleting a repository requires admin access. + * + * If an organization owner has configured the organization to prevent members from + * deleting organization-owned repositories, you will get a `403 Forbidden` + * response. + * + * OAuth app tokens and personal access tokens (classic) need the `delete_repo` + * scope to use this endpoint. + * + * @example + * ```ts + * await client.repos.delete({ owner: 'owner', repo: 'repo' }); + * ``` + */ + delete(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; + return this._client.delete(path2`/repos/${owner}/${repo}`, { + ...options, + headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + }); + } + /** + * Whether the authenticated user has starred the repository. + * + * @example + * ```ts + * await client.repos.checkStarred({ + * owner: 'owner', + * repo: 'repo', + * }); + * ``` + */ + checkStarred(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; + return this._client.get(path2`/user/starred/${owner}/${repo}`, { + ...options, + headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + }); + } + /** + * Compares two commits against one another. You can compare refs (branches or + * tags) and commit SHAs in the same repository, or you can compare refs and commit + * SHAs that exist in different repositories within the same repository network, + * including fork branches. For more information about how to view a repository's + * network, see + * "[Understanding connections between repositories](https://docs.github.com/repositories/viewing-activity-and-data-for-your-repository/understanding-connections-between-repositories)." + * + * This endpoint is equivalent to running the `git log BASE..HEAD` command, but it + * returns commits in a different order. The `git log BASE..HEAD` command returns + * commits in reverse chronological order, whereas the API returns commits in + * chronological order. + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.diff`**: Returns the diff of the commit. + * - **`application/vnd.github.patch`**: Returns the patch of the commit. Diffs + * with binary data will have no `patch` property. + * + * The API response includes details about the files that were changed between the + * two commits. This includes the status of the change (if a file was added, + * removed, modified, or renamed), and details of the change itself. For example, + * files with a `renamed` status have a `previous_filename` field showing the + * previous filename of the file, and files with a `modified` status have a `patch` + * field showing the changes made to the file. + * + * When calling this endpoint without any paging parameter (`per_page` or `page`), + * the returned list is limited to 250 commits, and the last commit in the list is + * the most recent of the entire comparison. + * + * **Working with large comparisons** + * + * To process a response with a large number of commits, use a query parameter + * (`per_page` or `page`) to paginate the results. When using pagination: + * + * - The list of changed files is only shown on the first page of results, and it + * includes up to 300 changed files for the entire comparison. + * - The results are returned in chronological order, but the last commit in the + * returned list may not be the most recent one in the entire set if there are + * more pages of results. + * + * For more information on working with pagination, see + * "[Using pagination in the REST API](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api)." + * + * **Signature verification object** + * + * The response will include a `verification` object that describes the result of + * verifying the commit's signature. The `verification` object includes the + * following fields: + * + * | Name | Type | Description | + * | ------------- | --------- | ------------------------------------------------------------------------------------------------ | + * | `verified` | `boolean` | Indicates whether GitHub considers the signature in this commit to be verified. | + * | `reason` | `string` | The reason for verified value. Possible values and their meanings are enumerated in table below. | + * | `signature` | `string` | The signature that was extracted from the commit. | + * | `payload` | `string` | The value that was signed. | + * | `verified_at` | `string` | The date the signature was verified by GitHub. | + * + * These are the possible values for `reason` in the `verification` object: + * + * | Value | Description | + * | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------- | + * | `expired_key` | The key that made the signature is expired. | + * | `not_signing_key` | The "signing" flag is not among the usage flags in the GPG key that made the signature. | + * | `gpgverify_error` | There was an error communicating with the signature verification service. | + * | `gpgverify_unavailable` | The signature verification service is currently unavailable. | + * | `unsigned` | The object does not include a signature. | + * | `unknown_signature_type` | A non-PGP signature was found in the commit. | + * | `no_user` | No user was associated with the `committer` email address in the commit. | + * | `unverified_email` | The `committer` email address in the commit was associated with a user, but the email address is not verified on their account. | + * | `bad_email` | The `committer` email address in the commit is not included in the identities of the PGP key that made the signature. | + * | `unknown_key` | The key that made the signature has not been registered with any user's account. | + * | `malformed_signature` | There was an error parsing the signature. | + * | `invalid` | The signature could not be cryptographically verified using the key whose key-id was found in the signature. | + * | `valid` | None of the above errors applied, so the signature is considered to be verified. | + * + * @example + * ```ts + * const response = await client.repos.compareCommits( + * 'basehead', + * { owner: 'owner', repo: 'repo' }, + * ); + * ``` + */ + compareCommits(basehead, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/compare/${basehead}`, { query, ...options }); } - obj = ""; - } - if (is_non_nullish_primitive2(obj) || is_buffer2(obj)) { - if (encoder) { - const key_value = encodeValuesOnly ? prefix : encoder(prefix, defaults2.encoder, charset, "key", format); - return [ - formatter?.(key_value) + "=" + // @ts-expect-error - formatter?.(encoder(obj, defaults2.encoder, charset, "value", format)) - ]; + /** + * Users with push access in a repository can create commit statuses for a given + * SHA. + * + * Note: there is a limit of 1000 statuses per `sha` and `context` within a + * repository. Attempts to create more than 1000 statuses will result in a + * validation error. + * + * @example + * ```ts + * const response = await client.repos.createCommitStatus( + * 'sha', + * { + * owner: 'owner', + * repo: 'repo', + * state: 'success', + * context: 'continuous-integration/jenkins', + * description: 'The build succeeded!', + * target_url: 'https://example.com/build/status', + * }, + * ); + * ``` + */ + createCommitStatus(sha, params, options) { + const { owner = this._client.owner, repo = this._client.repo, ...body } = params; + return this._client.post(path2`/repos/${owner}/${repo}/statuses/${sha}`, { body, ...options }); } - return [formatter?.(prefix) + "=" + formatter?.(String(obj))]; - } - const values = []; - if (typeof obj === "undefined") { - return values; - } - let obj_keys; - if (generateArrayPrefix === "comma" && isArray2(obj)) { - if (encodeValuesOnly && encoder) { - obj = maybe_map2(obj, encoder); + /** + * You can use this endpoint to trigger a webhook event called + * `repository_dispatch` when you want activity that happens outside of GitHub to + * trigger a GitHub Actions workflow or GitHub App webhook. You must configure your + * GitHub Actions workflow or GitHub App to run when the `repository_dispatch` + * event occurs. For an example `repository_dispatch` webhook payload, see + * "[RepositoryDispatchEvent](https://docs.github.com/webhooks/event-payloads/#repository_dispatch)." + * + * The `client_payload` parameter is available for any extra information that your + * workflow might need. This parameter is a JSON payload that will be passed on + * when the webhook event is dispatched. For example, the `client_payload` can + * include a message that a user would like to send using a GitHub Actions + * workflow. Or the `client_payload` can be used as a test to debug your workflow. + * + * This input example shows how you can use the `client_payload` as a test to debug + * your workflow. + * + * OAuth app tokens and personal access tokens (classic) need the `repo` scope to + * use this endpoint. + * + * @example + * ```ts + * await client.repos.createDispatchEvent({ + * owner: 'owner', + * repo: 'repo', + * event_type: 'on-demand-test', + * client_payload: { unit: false, integration: true }, + * }); + * ``` + */ + createDispatchEvent(params, options) { + const { owner = this._client.owner, repo = this._client.repo, ...body } = params; + return this._client.post(path2`/repos/${owner}/${repo}/dispatches`, { + body, + ...options, + headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + }); } - obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; - } else if (isArray2(filter)) { - obj_keys = filter; - } else { - const keys = Object.keys(obj); - obj_keys = sort ? keys.sort(sort) : keys; - } - const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix); - const adjusted_prefix = commaRoundTrip && isArray2(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix; - if (allowEmptyArrays && isArray2(obj) && obj.length === 0) { - return adjusted_prefix + "[]"; - } - for (let j = 0; j < obj_keys.length; ++j) { - const key = obj_keys[j]; - const value = ( - // @ts-ignore - typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key] - ); - if (skipNulls && value === null) { - continue; + /** + * Creates a new repository in the specified organization. The authenticated user + * must be a member of the organization. + * + * OAuth app tokens and personal access tokens (classic) need the `public_repo` or + * `repo` scope to create a public repository, and `repo` scope to create a private + * repository. + * + * @example + * ```ts + * const fullRepository = await client.repos.createForOrg( + * 'org', + * { + * name: 'Hello-World', + * description: 'This is your first repository', + * has_issues: true, + * has_projects: true, + * has_wiki: true, + * homepage: 'https://github.com', + * }, + * ); + * ``` + */ + createForOrg(org, body, options) { + return this._client.post(path2`/orgs/${org}/repos`, { body, ...options }); } - const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key; - const key_prefix = isArray2(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]"); - sideChannel.set(object, step); - const valueSideChannel = /* @__PURE__ */ new WeakMap(); - valueSideChannel.set(sentinel2, sideChannel); - push_to_array2(values, inner_stringify2( - value, - key_prefix, - generateArrayPrefix, - commaRoundTrip, - allowEmptyArrays, - strictNullHandling, - skipNulls, - encodeDotInKeys, - // @ts-ignore - generateArrayPrefix === "comma" && encodeValuesOnly && isArray2(obj) ? null : encoder, - filter, - sort, - allowDots, - serializeDate, - format, - formatter, - encodeValuesOnly, - charset, - valueSideChannel - )); - } - return values; -} -function normalize_stringify_options2(opts = defaults2) { - if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") { - throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); - } - if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") { - throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided"); - } - if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") { - throw new TypeError("Encoder has to be a function."); - } - const charset = opts.charset || defaults2.charset; - if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { - throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); - } - let format = default_format2; - if (typeof opts.format !== "undefined") { - if (!has2(formatters2, opts.format)) { - throw new TypeError("Unknown format option provided."); + /** + * Creates a new repository using a repository template. Use the `template_owner` + * and `template_repo` route parameters to specify the repository to use as the + * template. If the repository is not public, the authenticated user must own or be + * a member of an organization that owns the repository. To check if a repository + * is available to use as a template, get the repository's information using the + * [Get a repository](https://docs.github.com/rest/repos/repos#get-a-repository) + * endpoint and check that the `is_template` key is `true`. + * + * OAuth app tokens and personal access tokens (classic) need the `public_repo` or + * `repo` scope to create a public repository, and `repo` scope to create a private + * repository. + * + * @example + * ```ts + * const fullRepository = + * await client.repos.createFromTemplate('template_repo', { + * template_owner: 'template_owner', + * name: 'Hello-World', + * description: 'This is your first repository', + * owner: 'octocat', + * }); + * ``` + */ + createFromTemplate(templateRepo, params, options) { + const { template_owner, ...body } = params; + return this._client.post(path2`/repos/${template_owner}/${templateRepo}/generate`, { body, ...options }); } - format = opts.format; - } - const formatter = formatters2[format]; - let filter = defaults2.filter; - if (typeof opts.filter === "function" || isArray2(opts.filter)) { - filter = opts.filter; - } - let arrayFormat; - if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators2) { - arrayFormat = opts.arrayFormat; - } else if ("indices" in opts) { - arrayFormat = opts.indices ? "indices" : "repeat"; - } else { - arrayFormat = defaults2.arrayFormat; - } - if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") { - throw new TypeError("`commaRoundTrip` must be a boolean, or absent"); - } - const allowDots = typeof opts.allowDots === "undefined" ? !!opts.encodeDotInKeys === true ? true : defaults2.allowDots : !!opts.allowDots; - return { - addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults2.addQueryPrefix, - // @ts-ignore - allowDots, - allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults2.allowEmptyArrays, - arrayFormat, - charset, - charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults2.charsetSentinel, - commaRoundTrip: !!opts.commaRoundTrip, - delimiter: typeof opts.delimiter === "undefined" ? defaults2.delimiter : opts.delimiter, - encode: typeof opts.encode === "boolean" ? opts.encode : defaults2.encode, - encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults2.encodeDotInKeys, - encoder: typeof opts.encoder === "function" ? opts.encoder : defaults2.encoder, - encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults2.encodeValuesOnly, - filter, - format, - formatter, - serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults2.serializeDate, - skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults2.skipNulls, - // @ts-ignore - sort: typeof opts.sort === "function" ? opts.sort : null, - strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults2.strictNullHandling - }; -} -function stringify2(object, opts = {}) { - let obj = object; - const options = normalize_stringify_options2(opts); - let obj_keys; - let filter; - if (typeof options.filter === "function") { - filter = options.filter; - obj = filter("", obj); - } else if (isArray2(options.filter)) { - filter = options.filter; - obj_keys = filter; - } - const keys = []; - if (typeof obj !== "object" || obj === null) { - return ""; - } - const generateArrayPrefix = array_prefix_generators2[options.arrayFormat]; - const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip; - if (!obj_keys) { - obj_keys = Object.keys(obj); - } - if (options.sort) { - obj_keys.sort(options.sort); - } - const sideChannel = /* @__PURE__ */ new WeakMap(); - for (let i = 0; i < obj_keys.length; ++i) { - const key = obj_keys[i]; - if (options.skipNulls && obj[key] === null) { - continue; + /** + * Gets a redirect URL to download a tar archive for a repository. If you omit + * `:ref`, the repository’s default branch (usually `main`) will be used. Please + * make sure your HTTP framework is configured to follow redirects or you will need + * to use the `Location` header to make a second `GET` request. + * + * > [!NOTE] For private repositories, these links are temporary and expire after + * > five minutes. + * + * @example + * ```ts + * await client.repos.downloadTarball('ref', { + * owner: 'owner', + * repo: 'repo', + * }); + * ``` + */ + downloadTarball(ref, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/tarball/${ref}`, { + ...options, + headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + }); } - push_to_array2(keys, inner_stringify2( - obj[key], - key, - // @ts-expect-error - generateArrayPrefix, - commaRoundTrip, - options.allowEmptyArrays, - options.strictNullHandling, - options.skipNulls, - options.encodeDotInKeys, - options.encode ? options.encoder : null, - options.filter, - options.sort, - options.allowDots, - options.serializeDate, - options.format, - options.formatter, - options.encodeValuesOnly, - options.charset, - sideChannel - )); - } - const joined = keys.join(options.delimiter); - let prefix = options.addQueryPrefix === true ? "?" : ""; - if (options.charsetSentinel) { - if (options.charset === "iso-8859-1") { - prefix += "utf8=%26%2310003%3B&"; - } else { - prefix += "utf8=%E2%9C%93&"; + /** + * Gets a redirect URL to download a zip archive for a repository. If you omit + * `:ref`, the repository’s default branch (usually `main`) will be used. Please + * make sure your HTTP framework is configured to follow redirects or you will need + * to use the `Location` header to make a second `GET` request. + * + * > [!NOTE] For private repositories, these links are temporary and expire after + * > five minutes. If the repository is empty, you will receive a 404 when you + * > follow the redirect. + * + * @example + * ```ts + * await client.repos.downloadZipball('ref', { + * owner: 'owner', + * repo: 'repo', + * }); + * ``` + */ + downloadZipball(ref, params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/zipball/${ref}`, { + ...options, + headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + }); } - } - return joined.length > 0 ? prefix + joined : ""; -} - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/utils/log.mjs -var levelNumbers2 = { - off: 0, - error: 200, - warn: 300, - info: 400, - debug: 500 -}; -var parseLogLevel2 = (maybeLevel, sourceName, client) => { - if (!maybeLevel) { - return void 0; - } - if (hasOwn2(levelNumbers2, maybeLevel)) { - return maybeLevel; - } - loggerFor2(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers2))}`); - return void 0; -}; -function noop2() { -} -function makeLogFn2(fnLevel, logger2, logLevel) { - if (!logger2 || levelNumbers2[fnLevel] > levelNumbers2[logLevel]) { - return noop2; - } else { - return logger2[fnLevel].bind(logger2); - } -} -var noopLogger2 = { - error: noop2, - warn: noop2, - info: noop2, - debug: noop2 -}; -var cachedLoggers2 = /* @__PURE__ */ new WeakMap(); -function loggerFor2(client) { - const logger2 = client.logger; - const logLevel = client.logLevel ?? "off"; - if (!logger2) { - return noopLogger2; - } - const cachedLogger = cachedLoggers2.get(logger2); - if (cachedLogger && cachedLogger[0] === logLevel) { - return cachedLogger[1]; - } - const levelLogger = { - error: makeLogFn2("error", logger2, logLevel), - warn: makeLogFn2("warn", logger2, logLevel), - info: makeLogFn2("info", logger2, logLevel), - debug: makeLogFn2("debug", logger2, logLevel) - }; - cachedLoggers2.set(logger2, [logLevel, levelLogger]); - return levelLogger; -} -var formatRequestDetails2 = (details) => { - if (details.options) { - details.options = { ...details.options }; - delete details.options["headers"]; - } - if (details.headers) { - details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ - name, - name.toLowerCase() === "authorization" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value - ])); - } - if ("retryOfRequestLogID" in details) { - if (details.retryOfRequestLogID) { - details.retryOf = details.retryOfRequestLogID; + /** + * Enables an authenticated GitHub App to find the repository's installation + * information. The installation's account type will be either an organization or a + * user account, depending which account the repository belongs to. + * + * You must use a + * [JWT](https://docs.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) + * to access this endpoint. + * + * @example + * ```ts + * const installation = await client.repos.getInstallationInfo( + * { owner: 'owner', repo: 'repo' }, + * ); + * ``` + */ + getInstallationInfo(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/installation`, options); + } + /** + * This method returns the contents of the repository's license file, if one is + * detected. + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.raw+json`**: Returns the raw contents of the + * license. + * - **`application/vnd.github.html+json`**: Returns the license contents in HTML. + * Markup languages are rendered to HTML using GitHub's open-source + * [Markup library](https://github.com/github/markup). + * + * @example + * ```ts + * const response = await client.repos.getLicense({ + * owner: 'owner', + * repo: 'repo', + * }); + * ``` + */ + getLicense(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/license`, { query, ...options }); } - delete details.retryOfRequestLogID; - } - return details; -}; - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/parse.mjs -async function defaultParseResponse2(client, props) { - const { response, requestLogID, retryOfRequestLogID, startTime } = props; - const body = await (async () => { - if (response.status === 204) { - return null; + /** + * Get the code security configuration that manages a repository's code security + * settings. + * + * The authenticated user must be an administrator or security manager for the + * organization to use this endpoint. + * + * OAuth app tokens and personal access tokens (classic) need the `repo` scope to + * use this endpoint. + * + * @example + * ```ts + * const response = + * await client.repos.getSecurityConfiguration({ + * owner: 'owner', + * repo: 'repo', + * }); + * ``` + */ + getSecurityConfiguration(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/code-security-configuration`, options); } - if (props.options.__binaryResponse) { - return response; + /** + * Lists a detailed history of changes to a repository, such as pushes, merges, + * force pushes, and branch changes, and associates these changes with commits and + * users. + * + * For more information about viewing repository activity, see + * "[Viewing activity and data for your repository](https://docs.github.com/repositories/viewing-activity-and-data-for-your-repository)." + * + * @example + * ```ts + * const response = await client.repos.listActivity({ + * owner: 'owner', + * repo: 'repo', + * }); + * ``` + */ + listActivity(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/activity`, { query, ...options }); } - const contentType = response.headers.get("content-type"); - const mediaType = contentType?.split(";")[0]?.trim(); - const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json"); - if (isJSON) { - const contentLength = response.headers.get("content-length"); - if (contentLength === "0") { - return void 0; - } - const json = await response.json(); - return json; + /** + * > [!NOTE] This API is not built to serve real-time use cases. Depending on the + * > time of day, event latency can be anywhere from 30s to 6h. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const repoListEventsResponse of client.repos.listEvents( + * { owner: 'owner', repo: 'repo' }, + * )) { + * // ... + * } + * ``` + */ + listEvents(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.getAPIList(path2`/repos/${owner}/${repo}/events`, NumberedPage, { query, ...options }); } - const text = await response.text(); - return text; - })(); - loggerFor2(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails2({ - retryOfRequestLogID, - url: response.url, - status: response.status, - body, - durationMs: Date.now() - startTime - })); - return body; -} - -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/core/api-promise.mjs -var _APIPromise_client2; -var APIPromise2 = /* @__PURE__ */ (() => { - class APIPromise4 extends Promise { - constructor(client, responsePromise, parseResponse = defaultParseResponse2) { - super((resolve) => { - resolve(null); + /** + * Lists repositories that the authenticated user has explicit permission (`:read`, + * `:write`, or `:admin`) to access. + * + * The authenticated user has explicit permission to access repositories they own, + * repositories where they are a collaborator, and repositories that they can + * access through an organization membership. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const repository of client.repos.listForCurrentUser()) { + * // ... + * } + * ``` + */ + listForCurrentUser(query = {}, options) { + return this._client.getAPIList("/user/repos", NumberedPage, { query, ...options }); + } + /** + * Lists repositories for the specified organization. + * + * > [!NOTE] In order to see the `security_and_analysis` block for a repository you + * > must have admin permissions for the repository or be an owner or security + * > manager for the organization that owns the repository. For more information, + * > see + * > "[Managing security managers in your organization](https://docs.github.com/organizations/managing-peoples-access-to-your-organization-with-roles/managing-security-managers-in-your-organization)." + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const minimalRepository of client.repos.listForOrg( + * 'org', + * )) { + * // ... + * } + * ``` + */ + listForOrg(org, query = {}, options) { + return this._client.getAPIList(path2`/orgs/${org}/repos`, NumberedPage, { + query, + ...options }); - this.responsePromise = responsePromise; - this.parseResponse = parseResponse; - _APIPromise_client2.set(this, void 0); - __classPrivateFieldSet2(this, _APIPromise_client2, client, "f"); } - _thenUnwrap(transform) { - return new APIPromise4(__classPrivateFieldGet2(this, _APIPromise_client2, "f"), this.responsePromise, async (client, props) => transform(await this.parseResponse(client, props), props)); + /** + * Lists public repositories for the specified user. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const minimalRepository of client.repos.listForUser( + * 'username', + * )) { + * // ... + * } + * ``` + */ + listForUser(username, query = {}, options) { + return this._client.getAPIList(path2`/users/${username}/repos`, NumberedPage, { + query, + ...options + }); + } + /** + * Lists all public repositories in the order that they were created. + * + * Note: + * + * - For GitHub Enterprise Server, this endpoint will only list repositories + * available to all users on the enterprise. + * - Pagination is powered exclusively by the `since` parameter. Use the + * [Link header](https://docs.github.com/rest/guides/using-pagination-in-the-rest-api#using-link-headers) + * to get the URL for the next page of repositories. + * + * @example + * ```ts + * const minimalRepositories = await client.repos.listPublic(); + * ``` + */ + listPublic(query = {}, options) { + return this._client.get("/repositories", { query, ...options }); + } + /** + * Lists the people that have starred the repository. + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.star+json`**: Includes a timestamp of when the star + * was created. + * + * @example + * ```ts + * const response = await client.repos.listStargazers({ + * owner: 'owner', + * repo: 'repo', + * }); + * ``` + */ + listStargazers(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.get(path2`/repos/${owner}/${repo}/stargazers`, { query, ...options }); + } + /** + * Lists repositories the authenticated user has starred. + * + * This endpoint supports the following custom media types. For more information, + * see + * "[Media types](https://docs.github.com/rest/using-the-rest-api/getting-started-with-the-rest-api#media-types)." + * + * - **`application/vnd.github.star+json`**: Includes a timestamp of when the star + * was created. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const repository of client.repos.listStarred()) { + * // ... + * } + * ``` + */ + listStarred(query = {}, options) { + return this._client.getAPIList("/user/starred", NumberedPage, { query, ...options }); + } + /** + * Lists the people watching the specified repository. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const simpleUser of client.repos.listWatchers({ + * owner: 'owner', + * repo: 'repo', + * })) { + * // ... + * } + * ``` + */ + listWatchers(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo, ...query } = params ?? {}; + return this._client.getAPIList(path2`/repos/${owner}/${repo}/subscribers`, NumberedPage, { query, ...options }); } /** - * Gets the raw `Response` instance instead of parsing the response - * data. - * - * If you want to parse the response body but still get the `Response` - * instance, you can use {@link withResponse()}. + * Merge a branch * - * 👋 Getting the wrong TypeScript type for `Response`? - * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` - * to your `tsconfig.json`. + * @example + * ```ts + * const commit = await client.repos.mergeBranch({ + * owner: 'owner', + * repo: 'repo', + * base: 'master', + * head: 'cool_feature', + * commit_message: 'Shipped cool_feature!', + * }); + * ``` */ - asResponse() { - return this.responsePromise.then((p) => p.response); + mergeBranch(params, options) { + const { owner = this._client.owner, repo = this._client.repo, ...body } = params; + return this._client.post(path2`/repos/${owner}/${repo}/merges`, { body, ...options }); } /** - * Gets the parsed response data and the raw `Response` instance. - * - * If you just want to get the raw `Response` instance without parsing it, - * you can use {@link asResponse()}. + * Note that you'll need to set `Content-Length` to zero when calling out to this + * endpoint. For more information, see + * "[HTTP method](https://docs.github.com/rest/guides/getting-started-with-the-rest-api#http-method)." * - * 👋 Getting the wrong TypeScript type for `Response`? - * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` - * to your `tsconfig.json`. + * @example + * ```ts + * await client.repos.star({ owner: 'owner', repo: 'repo' }); + * ``` */ - async withResponse() { - const [data, response] = await Promise.all([this.parse(), this.asResponse()]); - return { data, response }; - } - parse() { - if (!this.parsedPromise) { - this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet2(this, _APIPromise_client2, "f"), data)); - } - return this.parsedPromise; + star(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; + return this._client.put(path2`/user/starred/${owner}/${repo}`, { + ...options, + headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + }); } - then(onfulfilled, onrejected) { - return this.parse().then(onfulfilled, onrejected); + /** + * Sync a branch of a forked repository to keep it up-to-date with the upstream + * repository. + * + * @example + * ```ts + * const response = await client.repos.syncFork({ + * owner: 'owner', + * repo: 'repo', + * branch: 'main', + * }); + * ``` + */ + syncFork(params, options) { + const { owner = this._client.owner, repo = this._client.repo, ...body } = params; + return this._client.post(path2`/repos/${owner}/${repo}/merge-upstream`, { body, ...options }); } - catch(onrejected) { - return this.parse().catch(onrejected); + /** + * A transfer request will need to be accepted by the new owner when transferring a + * personal repository to another user. The response will contain the original + * `owner`, and the transfer will continue asynchronously. For more details on the + * requirements to transfer personal and organization-owned repositories, see + * [about repository transfers](https://docs.github.com/articles/about-repository-transfers/). + * + * @example + * ```ts + * const minimalRepository = await client.repos.transfer({ + * owner: 'owner', + * repo: 'repo', + * new_owner: 'github', + * new_name: 'octorepo', + * team_ids: [12, 345], + * }); + * ``` + */ + transfer(params, options) { + const { owner = this._client.owner, repo = this._client.repo, ...body } = params; + return this._client.post(path2`/repos/${owner}/${repo}/transfer`, { body, ...options }); } - finally(onfinally) { - return this.parse().finally(onfinally); + /** + * Unstar a repository that the authenticated user has previously starred. + * + * @example + * ```ts + * await client.repos.unstar({ owner: 'owner', repo: 'repo' }); + * ``` + */ + unstar(params = {}, options) { + const { owner = this._client.owner, repo = this._client.repo } = params ?? {}; + return this._client.delete(path2`/user/starred/${owner}/${repo}`, { + ...options, + headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + }); } } - _APIPromise_client2 = /* @__PURE__ */ new WeakMap(); - return APIPromise4; + BaseRepos6._key = Object.freeze(["repos"]); + return BaseRepos6; })(); -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/utils/env.mjs +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/internal/utils/env.mjs var readEnv2 = (env) => { if (typeof globalThis.process !== "undefined") { return globalThis.process.env?.[env]?.trim() ?? void 0; @@ -15330,17 +14586,72 @@ var readEnv2 = (env) => { return void 0; }; -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/client.mjs -var _BaseGitLab_instances; -var _BaseGitLab_encoder; -var _BaseGitLab_baseURLOverridden; -var BaseGitLab = /* @__PURE__ */ (() => { - class BaseGitLab2 { +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/lib/auth.mjs +var import_jsonwebtoken = __toESM(require_jsonwebtoken(), 1); +async function getAuthToken({ authMethods, owner, repo, logger: logger2 }) { + const method = authMethods.find((method2) => method2.owner === owner) ?? authMethods.at(-1); + if (!method || method.owner !== owner && method.owner !== "*") { + throw new Error("No matching auth method found. Did you set a fallback auth method, with owner *?"); + } + if ("token" in method) { + return { authToken: method.token, expires: method.expires }; + } + const appAuth = await getAppToken(method); + const client = createClient({ + owner, + repo, + authToken: appAuth.authToken, + resources: [BaseRepos3, BaseOrgs, BaseInstallations] + }); + let installationId = method.installationId; + try { + if (!installationId) { + if (repo) { + const { id } = await client.repos.getInstallationInfo(); + installationId = id; + } else { + const { id } = await client.orgs.retrieveInstallation(owner); + installationId = id; + } + } + } catch (e) { + logger2?.warn(`No installation ID found for ${owner}/${repo}, using app token instead`, e); + } + if (!installationId) { + return appAuth; + } + try { + const { token, expires_at } = await client.apps.installations.createAccessToken(installationId); + return { authToken: token, expires: new Date(expires_at) }; + } catch (e) { + logger2?.warn(`Failed to get installation token for ${installationId}, using app token instead`, e); + } + return appAuth; +} +async function getAppToken(method) { + const iat = Math.floor(Date.now() / 1e3) - 30; + const exp = iat + 60 * 10; + const appToken = import_jsonwebtoken.default.sign({ iat, exp, iss: method.appId }, method.privateKey, { + algorithm: "RS256" + }); + const appTokenExpires = new Date(exp * 1e3); + return { authToken: appToken, expires: appTokenExpires }; +} + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/client.mjs +var _BaseGitHub_instances; +var _BaseGitHub_encoder; +var _BaseGitHub_baseURLOverridden; +var BaseGitHub = /* @__PURE__ */ (() => { + class BaseGitHub3 { /** - * API Client for interfacing with the GitLab API. + * API Client for interfacing with the GitHub API. * - * @param {string | undefined} [opts.apiToken=process.env['GITLAB_API_TOKEN'] ?? undefined] - * @param {string} [opts.baseURL=process.env['GITLAB_BASE_URL'] ?? https://gitlab.com/api/v4] - Override the default base URL for the API. + * @param {string | null | undefined} [opts.authToken=process.env['GITHUB_AUTH_TOKEN'] ?? null] + * @param {string | null | undefined} [opts.owner] + * @param {string | null | undefined} [opts.repo] + * @param {string | null | undefined} [opts.webhookSecret=process.env['GITHUB_WEBHOOK_SECRET'] ?? null] + * @param {string} [opts.baseURL=process.env['GITHUB_BASE_URL'] ?? https://api.github.com] - Override the default base URL for the API. * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. @@ -15348,4618 +14659,5324 @@ var BaseGitLab = /* @__PURE__ */ (() => { * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. */ - constructor({ baseURL = readEnv2("GITLAB_BASE_URL"), apiToken = readEnv2("GITLAB_API_TOKEN"), ...opts } = {}) { - _BaseGitLab_instances.add(this); - _BaseGitLab_encoder.set(this, void 0); - if (apiToken === void 0) { - throw new GitLabError("The GITLAB_API_TOKEN environment variable is missing or empty; either provide it, or instantiate the GitLab client with an apiToken option, like new GitLab({ apiToken: 'My API Token' })."); - } + constructor({ baseURL = readEnv2("GITHUB_BASE_URL"), authToken = readEnv2("GITHUB_AUTH_TOKEN") ?? null, owner = null, repo = null, webhookSecret = readEnv2("GITHUB_WEBHOOK_SECRET") ?? null, ...opts } = {}) { + _BaseGitHub_instances.add(this); + _BaseGitHub_encoder.set(this, void 0); const options = { - apiToken, + authToken, + owner, + repo, + webhookSecret, ...opts, - baseURL: baseURL || `https://gitlab.com/api/v4` + baseURL: baseURL || `https://api.github.com` }; this.baseURL = options.baseURL; - this.timeout = options.timeout ?? BaseGitLab2.DEFAULT_TIMEOUT; + this.timeout = options.timeout ?? BaseGitHub3.DEFAULT_TIMEOUT; this.logger = options.logger ?? console; const defaultLogLevel = "warn"; this.logLevel = defaultLogLevel; - this.logLevel = parseLogLevel2(options.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel2(readEnv2("GITLAB_LOG"), "process.env['GITLAB_LOG']", this) ?? defaultLogLevel; + this.logLevel = parseLogLevel2(options.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel2(readEnv2("GITHUB_LOG"), "process.env['GITHUB_LOG']", this) ?? defaultLogLevel; this.fetchOptions = options.fetchOptions; this.maxRetries = options.maxRetries ?? 2; this.fetch = options.fetch ?? getDefaultFetch2(); - __classPrivateFieldSet2(this, _BaseGitLab_encoder, FallbackEncoder2, "f"); + __classPrivateFieldSet2(this, _BaseGitHub_encoder, FallbackEncoder2, "f"); this._options = options; - this.apiToken = apiToken; + this.authToken = authToken; + this.owner = owner; + this.repo = repo; + this.webhookSecret = webhookSecret; + } + /** + * Create a new client instance re-using the same options given to the current client with optional overriding. + */ + withOptions(options) { + const client = new this.constructor({ + ...this._options, + baseURL: this.baseURL, + maxRetries: this.maxRetries, + timeout: this.timeout, + logger: this.logger, + logLevel: this.logLevel, + fetch: this.fetch, + fetchOptions: this.fetchOptions, + authToken: this.authToken, + owner: this.owner, + repo: this.repo, + webhookSecret: this.webhookSecret, + ...options + }); + return client; + } + /** + * Get Hypermedia links to resources accessible in GitHub's REST API + */ + retrieve(options) { + return this.get("/", options); + } + /** + * Get a random sentence from the Zen of GitHub + */ + zen(options) { + return this.get("/zen", { + ...options, + headers: buildHeaders2([{ Accept: "text/plain" }, options?.headers]) + }); + } + defaultQuery() { + return this._options.defaultQuery; + } + validateHeaders({ values, nulls }) { + return; + } + async authHeaders(opts) { + if (this.authToken == null) { + return void 0; + } + return buildHeaders2([{ Authorization: `Bearer ${this.authToken}` }]); } /** - * Create a new client instance re-using the same options given to the current client with optional overriding. + * Given a list of available auth methods, get an auth token to access the + * given GitHub `owner` (and optionally `repo`), and set it on this client. */ - withOptions(options) { - const client = new this.constructor({ - ...this._options, - baseURL: this.baseURL, - maxRetries: this.maxRetries, - timeout: this.timeout, - logger: this.logger, - logLevel: this.logLevel, - fetch: this.fetch, - fetchOptions: this.fetchOptions, - apiToken: this.apiToken, - ...options + async getAuthToken(opts) { + if (this.authToken != null) { + return this.authToken; + } + const owner = opts.owner ?? this.owner; + const repo = opts.repo ?? this.repo; + if (owner == null) { + throw new Error("Specify an owner to get a token for."); + } + const { authToken } = await getAuthToken({ + authMethods: opts.authMethods, + owner, + repo, + logger: this.logger }); - return client; + this.authToken = authToken; + return authToken; + } + stringifyQuery(query) { + return stringify2(query, { arrayFormat: "comma" }); + } + getUserAgent() { + return `${this.constructor.name}/JS ${VERSION2}`; + } + defaultIdempotencyKey() { + return `stainless-node-retry-${uuid42()}`; + } + makeStatusError(status, error, message, headers) { + return APIError2.generate(status, error, message, headers); + } + buildURL(path7, query, defaultBaseURL) { + const baseURL = !__classPrivateFieldGet2(this, _BaseGitHub_instances, "m", _BaseGitHub_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL; + const url = isAbsoluteURL2(path7) ? new URL(path7) : new URL(baseURL + (baseURL.endsWith("/") && path7.startsWith("/") ? path7.slice(1) : path7)); + const defaultQuery = this.defaultQuery(); + if (!isEmptyObj2(defaultQuery)) { + query = { ...defaultQuery, ...query }; + } + if (typeof query === "object" && query && !Array.isArray(query)) { + url.search = this.stringifyQuery(query); + } + return url.toString(); } /** - * Execute a GLQL (GitLab Query Language) query + * Used as a callback for mutating the given `FinalRequestOptions` object. */ - glql(body, options) { - return this.post("/glql", { body, ...options }); + async prepareOptions(options) { } /** - * This feature was introduced in GitLab 11.0. + * Used as a callback for mutating the given `RequestInit` object. + * + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. */ - markdown(body, options) { - return this.post("/markdown", { body, ...options }); + async prepareRequest(request, { url, options }) { + } + get(path7, opts) { + return this.methodRequest("get", path7, opts); + } + post(path7, opts) { + return this.methodRequest("post", path7, opts); + } + patch(path7, opts) { + return this.methodRequest("patch", path7, opts); + } + put(path7, opts) { + return this.methodRequest("put", path7, opts); + } + delete(path7, opts) { + return this.methodRequest("delete", path7, opts); + } + methodRequest(method, path7, opts) { + return this.request(Promise.resolve(opts).then((opts2) => { + return { method, path: path7, ...opts2 }; + })); + } + request(options, remainingRetries = null) { + return new APIPromise2(this, this.makeRequest(options, remainingRetries, void 0)); + } + async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { + const options = await optionsInput; + const maxRetries = options.maxRetries ?? this.maxRetries; + if (retriesRemaining == null) { + retriesRemaining = maxRetries; + } + await this.prepareOptions(options); + const { req, url, timeout } = await this.buildRequest(options, { + retryCount: maxRetries - retriesRemaining + }); + await this.prepareRequest(req, { url, options }); + const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0"); + const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`; + const startTime = Date.now(); + loggerFor2(this).debug(`[${requestLogID}] sending request`, formatRequestDetails2({ + retryOfRequestLogID, + method: options.method, + url, + options, + headers: req.headers + })); + if (options.signal?.aborted) { + throw new APIUserAbortError2(); + } + const controller = new AbortController(); + const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError2); + const headersTime = Date.now(); + if (response instanceof globalThis.Error) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + if (options.signal?.aborted) { + throw new APIUserAbortError2(); + } + const isTimeout = isAbortError2(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : "")); + if (retriesRemaining) { + loggerFor2(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`); + loggerFor2(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails2({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); + } + loggerFor2(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`); + loggerFor2(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails2({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + if (isTimeout) { + throw new APIConnectionTimeoutError2(); + } + throw new APIConnectionError2({ cause: response }); + } + const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`; + if (!response.ok) { + const shouldRetry = await this.shouldRetry(response); + if (retriesRemaining && shouldRetry) { + const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`; + await CancelReadableStream2(response.body); + loggerFor2(this).info(`${responseInfo} - ${retryMessage2}`); + loggerFor2(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails2({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); + } + const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; + loggerFor2(this).info(`${responseInfo} - ${retryMessage}`); + const errText = await response.text().catch((err2) => castToError2(err2).message); + const errJSON = safeJSON2(errText); + const errMessage = errJSON ? void 0 : errText; + loggerFor2(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails2({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + message: errMessage, + durationMs: Date.now() - startTime + })); + const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); + throw err; + } + loggerFor2(this).info(responseInfo); + loggerFor2(this).debug(`[${requestLogID}] response start`, formatRequestDetails2({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; + } + getAPIList(path7, Page2, opts) { + return this.requestAPIList(Page2, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path7, ...opts2 })) : { method: "get", path: path7, ...opts }); + } + requestAPIList(Page2, options) { + const request = this.makeRequest(options, null, void 0); + return new PagePromise2(this, request, Page2); + } + async fetchWithTimeout(url, init, ms, controller) { + const { signal, method, ...options } = init || {}; + const abort = this._makeAbort(controller); + if (signal) + signal.addEventListener("abort", abort, { once: true }); + const timeout = setTimeout(abort, ms); + const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body; + const fetchOptions = { + signal: controller.signal, + ...isReadableBody ? { duplex: "half" } : {}, + method: "GET", + ...options + }; + if (method) { + fetchOptions.method = method.toUpperCase(); + } + try { + return await this.fetch.call(void 0, url, fetchOptions); + } finally { + clearTimeout(timeout); + } + } + async shouldRetry(response) { + const shouldRetryHeader = response.headers.get("x-should-retry"); + if (shouldRetryHeader === "true") + return true; + if (shouldRetryHeader === "false") + return false; + if (response.status === 408) + return true; + if (response.status === 409) + return true; + if (response.status === 429) + return true; + if (response.status >= 500) + return true; + return false; + } + async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { + let timeoutMillis; + const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms"); + if (retryAfterMillisHeader) { + const timeoutMs = parseFloat(retryAfterMillisHeader); + if (!Number.isNaN(timeoutMs)) { + timeoutMillis = timeoutMs; + } + } + const retryAfterHeader = responseHeaders?.get("retry-after"); + if (retryAfterHeader && !timeoutMillis) { + const timeoutSeconds = parseFloat(retryAfterHeader); + if (!Number.isNaN(timeoutSeconds)) { + timeoutMillis = timeoutSeconds * 1e3; + } else { + timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); + } + } + if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1e3)) { + const maxRetries = options.maxRetries ?? this.maxRetries; + timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + } + await sleep2(timeoutMillis); + return this.makeRequest(options, retriesRemaining - 1, requestLogID); } - /** - * This feature was introduced in GitLab 17.5. \ - * This feature is currently in an experimental state. \ - * This feature is behind the `allow_organization_creation` feature flag. \ - * In GitLab 18.3, feature flag changed to `organization_switching`. - */ - organizations(body, options) { - return this.post("/organizations", multipartFormRequestOptions({ body, ...options }, this)); + calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { + const initialRetryDelay = 0.5; + const maxRetryDelay = 8; + const numRetries = maxRetries - retriesRemaining; + const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); + const jitter = 1 - Math.random() * 0.25; + return sleepSeconds * jitter * 1e3; } - /** - * Return avatar url for a user - */ - retrieveAvatar(query, options) { - return this.get("/avatar", { query, ...options }); + async buildRequest(inputOptions, { retryCount = 0 } = {}) { + const options = { ...inputOptions }; + const { method, path: path7, query, defaultBaseURL } = options; + const url = this.buildURL(path7, query, defaultBaseURL); + if ("timeout" in options) + validatePositiveInteger2("timeout", options.timeout); + options.timeout = options.timeout ?? this.timeout; + const { bodyHeaders, body } = this.buildBody({ options }); + const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); + const req = { + method, + headers: reqHeaders, + ...options.signal && { signal: options.signal }, + ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" }, + ...body && { body }, + ...this.fetchOptions ?? {}, + ...options.fetchOptions ?? {} + }; + return { req, url, timeout: options.timeout }; } - /** - * Get a list of all deploy tokens across the GitLab instance. This endpoint - * requires administrator access. This feature was introduced in GitLab 12.9. - */ - retrieveDeployTokens(query = {}, options) { - return this.get("/deploy_tokens", { query, ...options }); + async buildHeaders({ options, method, bodyHeaders, retryCount }) { + let idempotencyHeaders = {}; + if (this.idempotencyHeader && method !== "get") { + if (!options.idempotencyKey) + options.idempotencyKey = this.defaultIdempotencyKey(); + idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; + } + const headers = buildHeaders2([ + idempotencyHeaders, + { + Accept: "application/json", + "User-Agent": this.getUserAgent(), + "X-Stainless-Retry-Count": String(retryCount), + ...options.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options.timeout / 1e3)) } : {}, + ...getPlatformHeaders2() + }, + await this.authHeaders(options), + this._options.defaultHeaders, + bodyHeaders, + options.headers + ]); + this.validateHeaders(headers); + return headers.values; } - /** - * This feature was introduced in GitLab 17.9. It will be removed in 18.0. - */ - retrieveDiscoverCertBasedClusters(query, options) { - return this.get("/discover-cert-based-clusters", { query, ...options }); + _makeAbort(controller) { + return () => controller.abort(); } - /** - * This feature was introduced in GitLab 9.3. - */ - retrieveEvents(query = {}, options) { - return this.get("/events", { query, ...options }); + buildBody({ options: { body, headers: rawHeaders } }) { + if (!body) { + return { bodyHeaders: void 0, body: void 0 }; + } + const headers = buildHeaders2([rawHeaders]); + if ( + // Pass raw type verbatim + ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && // Preserve legacy string encoding behavior for now + headers.values.has("content-type") || // `Blob` is superset of `File` + globalThis.Blob && body instanceof globalThis.Blob || // `FormData` -> `multipart/form-data` + body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded` + body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`) + globalThis.ReadableStream && body instanceof globalThis.ReadableStream + ) { + return { bodyHeaders: void 0, body }; + } else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) { + return { bodyHeaders: void 0, body: ReadableStreamFrom2(body) }; + } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") { + return { + bodyHeaders: { "content-type": "application/x-www-form-urlencoded" }, + body: this.stringifyQuery(body) + }; + } else { + return __classPrivateFieldGet2(this, _BaseGitHub_encoder, "f").call(this, { body, headers }); + } } - /** - * Get a list of all experiments. Each experiment has an enabled status that - * indicates whetherthe experiment is enabled globally, or only in specific - * contexts. - */ - retrieveExperiments(options) { - return this.get("/experiments", options); + } + _BaseGitHub_encoder = /* @__PURE__ */ new WeakMap(), _BaseGitHub_instances = /* @__PURE__ */ new WeakSet(), _BaseGitHub_baseURLOverridden = function _BaseGitHub_baseURLOverridden2() { + return this.baseURL !== "https://api.github.com"; + }; + BaseGitHub3.DEFAULT_TIMEOUT = 6e4; + return BaseGitHub3; +})(); + +// node_modules/.pnpm/@stainless-api+github-internal@0.25.1/node_modules/@stainless-api/github-internal/tree-shakable.mjs +function createClient(options) { + const client = new BaseGitHub(options); + for (const ResourceClass of options.resources) { + const resourceInstance = new ResourceClass(client); + let object = client; + for (const part of ResourceClass._key.slice(0, -1)) { + if (hasOwn2(object, part)) { + object = object[part]; + } else { + Object.defineProperty(object, part, { + value: object = {}, + configurable: true, + enumerable: true, + writable: true + }); + } } - /** - * Get currently authenticated user's issues statistics - */ - retrieveIssuesStatistics(query = {}, options) { - return this.get("/issues_statistics", { - query, - ...options, - headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + const name = ResourceClass._key.at(-1); + if (!hasOwn2(object, name)) { + Object.defineProperty(object, name, { + value: resourceInstance, + configurable: true, + enumerable: true, + writable: true }); + } else { + if (object[name] instanceof APIResource2) { + throw new TypeError(`Resource at ${ResourceClass._key.join(".")} already exists!`); + } else { + object[name] = Object.assign(resourceInstance, object[name]); + } } - /** - * Get a list of licenses - */ - retrieveLicenses(options) { - return this.get("/licenses", options); - } - /** - * Get all merge requests the authenticated user has access to. By default it - * returns only merge requests created by the current user. To get all merge - * requests, use parameter `scope=all`. - */ - retrieveMergeRequests(query = {}, options) { - return this.get("/merge_requests", { query, ...options }); - } - /** - * This feature was introduced in GitLab 15.2. - */ - retrieveMetadata(options) { - return this.get("/metadata", options); - } - /** - * This feature was introduced in GitLab 10.5. - */ - retrieveSearch(query, options) { - return this.get("/search", { - query, - ...options, - headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) - }); + } + return client; +} + +// src/compat/github/context.ts +var fs = __toESM(require("node:fs")); +var cachedContext; +function getGitHubContext() { + if (cachedContext) { + return cachedContext; + } + const [owner, repo] = process.env.GITHUB_REPOSITORY?.split("/") ?? []; + const runID = process.env.GITHUB_RUN_ID; + if (!owner || !repo || !runID) { + throw new Error( + "Expected env vars GITHUB_REPOSITORY and GITHUB_RUN_ID to be set." + ); + } + const host = process.env.GITHUB_SERVER_URL || "https://github.com"; + const apiURL = process.env.GITHUB_API_URL || "https://api.github.com"; + const runURL = `${host}/${owner}/${repo}/actions/runs/${runID}`; + let defaultBranch = null; + let prNumber = null; + try { + const eventPath = process.env.GITHUB_EVENT_PATH; + const payload = eventPath && fs.existsSync(eventPath) && JSON.parse(fs.readFileSync(eventPath, "utf-8")); + const maybeDefaultBranch = payload?.repository?.default_branch; + if (typeof maybeDefaultBranch === "string") { + defaultBranch = maybeDefaultBranch; } - /** - * Assigned open issues, assigned MRs and pending todos count - */ - retrieveUserCounts(options) { - return this.get("/user_counts", options); + const maybePRNumber = parseInt( + payload?.pull_request?.number ?? process.env.PR_NUMBER ?? "", + 10 + ); + if (Number.isInteger(maybePRNumber)) { + prNumber = maybePRNumber; } - /** - * This feature was introduced in GitLab 8.13 and deprecated in 15.5. We recommend - * you instead use the Metadata API. - */ - retrieveVersion(options) { - return this.get("/version", options); + } catch (e) { + throw new Error(`Failed to parse GitHub event: ${e}`); + } + const refName = process.env.GITHUB_REF_NAME || null; + const sha = process.env.GITHUB_SHA || null; + cachedContext = { + provider: "github", + host, + owner, + repo, + urls: { api: apiURL, run: runURL }, + names: { ci: "GitHub Actions", pr: "PR", provider: "GitHub" }, + defaultBranch, + prNumber, + refName, + sha + }; + logger.debug("GitHub context", cachedContext); + return cachedContext; +} + +// src/compat/github/api.ts +var GitHubClient = class { + client; + constructor(token) { + this.client = createClient({ + authToken: token, + baseURL: getGitHubContext().urls.api, + owner: getGitHubContext().owner, + repo: getGitHubContext().repo, + resources: [BaseCommits, BaseComments2, BasePulls], + logLevel: "warn", + logger + }); + } + async listComments(prNumber) { + const { data } = await this.client.repos.issues.comments.list(prNumber); + return data.map((c) => ({ id: c.id, body: c.body ?? "" })); + } + async createComment(prNumber, props) { + const data = await this.client.repos.issues.comments.create( + prNumber, + props + ); + return { id: data.id, body: data.body }; + } + async updateComment(_prNumber, { id, body }) { + const data = await this.client.repos.issues.comments.update(id, { + body + }); + return { id: data.id, body: data.body }; + } + async getPullRequest(number) { + const data = await this.client.repos.pulls.retrieve(number); + return { + number, + state: data.merged_at ? "merged" : data.state, + title: data.title, + base_sha: data.base.sha, + base_ref: data.base.ref, + head_ref: data.head.ref, + head_sha: data.head.sha, + merge_commit_sha: data.merge_commit_sha + }; + } + async getPullRequestForCommit(sha) { + const pullRequests = await this.client.repos.commits.listPullRequests(sha).then( + ({ data }) => data.filter((c) => c.merged_at || c.state !== "closed") + ).catch((err) => { + if (err instanceof APIError2 && (err.status === 401 || err.status === 403 || err.status === 404)) { + return []; + } + throw err; + }); + if (pullRequests.length === 0) { + return null; } - defaultQuery() { - return this._options.defaultQuery; + if (pullRequests.length > 1) { + logger.warn( + `Multiple pull requests found for commit; only using first.`, + { commit: sha, pulls: pullRequests.map((c) => c.number) } + ); } - validateHeaders({ values, nulls }) { - return; + const pull = pullRequests[0]; + return { + number: pull.number, + state: pull.merged_at ? "merged" : pull.state, + title: pull.title, + base_sha: pull.base.sha, + base_ref: pull.base.ref, + head_ref: pull.head.ref, + head_sha: pull.head.sha, + merge_commit_sha: pull.merge_commit_sha + }; + } +}; +var cachedClient; +function getGitHubClient() { + if (cachedClient !== void 0) { + return cachedClient; + } + const token = getInput("github_token"); + if (token) { + cachedClient = new GitHubClient(token); + } else { + logger.info("No GitHub token found via input 'github_token'."); + cachedClient = null; + } + return cachedClient; +} + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/errors.mjs +function isAbortError3(err) { + return typeof err === "object" && err !== null && // Spec-compliant fetch implementations + ("name" in err && err.name === "AbortError" || // Expo fetch + "message" in err && String(err.message).includes("FetchRequestCanceledException")); +} +var castToError3 = (err) => { + if (err instanceof Error) + return err; + if (typeof err === "object" && err !== null) { + try { + if (Object.prototype.toString.call(err) === "[object Error]") { + const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); + if (err.stack) + error.stack = err.stack; + if (err.cause && !error.cause) + error.cause = err.cause; + if (err.name) + error.name = err.name; + return error; + } + } catch { } - async authHeaders(opts) { - return buildHeaders2([{ Authorization: `Bearer ${this.apiToken}` }]); + try { + return new Error(JSON.stringify(err)); + } catch { } - stringifyQuery(query) { - return stringify2(query, { arrayFormat: "comma" }); + } + return new Error(err); +}; + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/core/error.mjs +var GitLabError = /* @__PURE__ */ (() => { + class GitLabError2 extends Error { + } + return GitLabError2; +})(); +var APIError3 = class _APIError extends GitLabError { + constructor(status, error, message, headers) { + super(`${_APIError.makeMessage(status, error, message)}`); + this.status = status; + this.headers = headers; + this.error = error; + } + static makeMessage(status, error, message) { + const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message; + if (status && msg) { + return `${status} ${msg}`; } - getUserAgent() { - return `${this.constructor.name}/JS ${VERSION2}`; + if (status) { + return `${status} status code (no body)`; } - defaultIdempotencyKey() { - return `stainless-node-retry-${uuid42()}`; + if (msg) { + return msg; } - makeStatusError(status, error, message, headers) { - return APIError2.generate(status, error, message, headers); + return "(no status code or body)"; + } + static generate(status, errorResponse, message, headers) { + if (!status || !headers) { + return new APIConnectionError3({ message, cause: castToError3(errorResponse) }); } - buildURL(path7, query, defaultBaseURL) { - const baseURL = !__classPrivateFieldGet2(this, _BaseGitLab_instances, "m", _BaseGitLab_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL; - const url = isAbsoluteURL2(path7) ? new URL(path7) : new URL(baseURL + (baseURL.endsWith("/") && path7.startsWith("/") ? path7.slice(1) : path7)); - const defaultQuery = this.defaultQuery(); - if (!isEmptyObj2(defaultQuery)) { - query = { ...defaultQuery, ...query }; - } - if (typeof query === "object" && query && !Array.isArray(query)) { - url.search = this.stringifyQuery(query); - } - return url.toString(); + const error = errorResponse; + if (status === 400) { + return new BadRequestError3(status, error, message, headers); } - /** - * Used as a callback for mutating the given `FinalRequestOptions` object. - */ - async prepareOptions(options) { + if (status === 401) { + return new AuthenticationError3(status, error, message, headers); } - /** - * Used as a callback for mutating the given `RequestInit` object. - * - * This is useful for cases where you want to add certain headers based off of - * the request properties, e.g. `method` or `url`. - */ - async prepareRequest(request, { url, options }) { + if (status === 403) { + return new PermissionDeniedError3(status, error, message, headers); } - get(path7, opts) { - return this.methodRequest("get", path7, opts); + if (status === 404) { + return new NotFoundError3(status, error, message, headers); } - post(path7, opts) { - return this.methodRequest("post", path7, opts); + if (status === 409) { + return new ConflictError3(status, error, message, headers); } - patch(path7, opts) { - return this.methodRequest("patch", path7, opts); + if (status === 422) { + return new UnprocessableEntityError3(status, error, message, headers); } - put(path7, opts) { - return this.methodRequest("put", path7, opts); + if (status === 429) { + return new RateLimitError3(status, error, message, headers); } - delete(path7, opts) { - return this.methodRequest("delete", path7, opts); + if (status >= 500) { + return new InternalServerError3(status, error, message, headers); } - methodRequest(method, path7, opts) { - return this.request(Promise.resolve(opts).then((opts2) => { - return { method, path: path7, ...opts2 }; - })); + return new _APIError(status, error, message, headers); + } +}; +var APIUserAbortError3 = class extends APIError3 { + constructor({ message } = {}) { + super(void 0, void 0, message || "Request was aborted.", void 0); + } +}; +var APIConnectionError3 = class extends APIError3 { + constructor({ message, cause }) { + super(void 0, void 0, message || "Connection error.", void 0); + if (cause) + this.cause = cause; + } +}; +var APIConnectionTimeoutError3 = class extends APIConnectionError3 { + constructor({ message } = {}) { + super({ message: message ?? "Request timed out." }); + } +}; +var BadRequestError3 = class extends APIError3 { +}; +var AuthenticationError3 = class extends APIError3 { +}; +var PermissionDeniedError3 = class extends APIError3 { +}; +var NotFoundError3 = class extends APIError3 { +}; +var ConflictError3 = class extends APIError3 { +}; +var UnprocessableEntityError3 = class extends APIError3 { +}; +var RateLimitError3 = class extends APIError3 { +}; +var InternalServerError3 = class extends APIError3 { +}; + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/core/resource.mjs +var APIResource3 = /* @__PURE__ */ (() => { + class APIResource4 { + constructor(client) { + this._client = client; } - request(options, remainingRetries = null) { - return new APIPromise2(this, this.makeRequest(options, remainingRetries, void 0)); + } + APIResource4._key = []; + return APIResource4; +})(); + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/utils/values.mjs +var startsWithSchemeRegexp3 = /^[a-z][a-z0-9+.-]*:/i; +var isAbsoluteURL3 = (url) => { + return startsWithSchemeRegexp3.test(url); +}; +var isArray3 = (val) => (isArray3 = Array.isArray, isArray3(val)); +var isReadonlyArray3 = isArray3; +function isEmptyObj3(obj) { + if (!obj) + return true; + for (const _k in obj) + return false; + return true; +} +function hasOwn3(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +var validatePositiveInteger3 = (name, n) => { + if (typeof n !== "number" || !Number.isInteger(n)) { + throw new GitLabError(`${name} must be an integer`); + } + if (n < 0) { + throw new GitLabError(`${name} must be a positive integer`); + } + return n; +}; +var safeJSON3 = (text) => { + try { + return JSON.parse(text); + } catch (err) { + return void 0; + } +}; + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/headers.mjs +var brand_privateNullableHeaders3 = /* @__PURE__ */ Symbol("brand.privateNullableHeaders"); +function* iterateHeaders3(headers) { + if (!headers) + return; + if (brand_privateNullableHeaders3 in headers) { + const { values, nulls } = headers; + yield* values.entries(); + for (const name of nulls) { + yield [name, null]; } - async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { - const options = await optionsInput; - const maxRetries = options.maxRetries ?? this.maxRetries; - if (retriesRemaining == null) { - retriesRemaining = maxRetries; - } - await this.prepareOptions(options); - const { req, url, timeout } = await this.buildRequest(options, { - retryCount: maxRetries - retriesRemaining - }); - await this.prepareRequest(req, { url, options }); - const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0"); - const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`; - const startTime = Date.now(); - loggerFor2(this).debug(`[${requestLogID}] sending request`, formatRequestDetails2({ - retryOfRequestLogID, - method: options.method, - url, - options, - headers: req.headers - })); - if (options.signal?.aborted) { - throw new APIUserAbortError2(); - } - const controller = new AbortController(); - const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError2); - const headersTime = Date.now(); - if (response instanceof globalThis.Error) { - const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; - if (options.signal?.aborted) { - throw new APIUserAbortError2(); - } - const isTimeout = isAbortError2(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : "")); - if (retriesRemaining) { - loggerFor2(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`); - loggerFor2(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails2({ - retryOfRequestLogID, - url, - durationMs: headersTime - startTime, - message: response.message - })); - return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); - } - loggerFor2(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`); - loggerFor2(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails2({ - retryOfRequestLogID, - url, - durationMs: headersTime - startTime, - message: response.message - })); - if (isTimeout) { - throw new APIConnectionTimeoutError2(); - } - throw new APIConnectionError2({ cause: response }); - } - const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`; - if (!response.ok) { - const shouldRetry = await this.shouldRetry(response); - if (retriesRemaining && shouldRetry) { - const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`; - await CancelReadableStream2(response.body); - loggerFor2(this).info(`${responseInfo} - ${retryMessage2}`); - loggerFor2(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails2({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - durationMs: headersTime - startTime - })); - return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); - } - const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; - loggerFor2(this).info(`${responseInfo} - ${retryMessage}`); - const errText = await response.text().catch((err2) => castToError2(err2).message); - const errJSON = safeJSON2(errText); - const errMessage = errJSON ? void 0 : errText; - loggerFor2(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails2({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - message: errMessage, - durationMs: Date.now() - startTime - })); - const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); - throw err; + return; + } + let shouldClear = false; + let iter; + if (headers instanceof Headers) { + iter = headers.entries(); + } else if (isReadonlyArray3(headers)) { + iter = headers; + } else { + shouldClear = true; + iter = Object.entries(headers ?? {}); + } + for (let row of iter) { + const name = row[0]; + if (typeof name !== "string") + throw new TypeError("expected header name to be a string"); + const values = isReadonlyArray3(row[1]) ? row[1] : [row[1]]; + let didClear = false; + for (const value of values) { + if (value === void 0) + continue; + if (shouldClear && !didClear) { + didClear = true; + yield [name, null]; } - loggerFor2(this).info(responseInfo); - loggerFor2(this).debug(`[${requestLogID}] response start`, formatRequestDetails2({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - durationMs: headersTime - startTime - })); - return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; + yield [name, value]; } - async fetchWithTimeout(url, init, ms, controller) { - const { signal, method, ...options } = init || {}; - const abort = this._makeAbort(controller); - if (signal) - signal.addEventListener("abort", abort, { once: true }); - const timeout = setTimeout(abort, ms); - const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body; - const fetchOptions = { - signal: controller.signal, - ...isReadableBody ? { duplex: "half" } : {}, - method: "GET", - ...options - }; - if (method) { - fetchOptions.method = method.toUpperCase(); + } +} +var buildHeaders3 = (newHeaders) => { + const targetHeaders = new Headers(); + const nullHeaders = /* @__PURE__ */ new Set(); + for (const headers of newHeaders) { + const seenHeaders = /* @__PURE__ */ new Set(); + for (const [name, value] of iterateHeaders3(headers)) { + const lowerName = name.toLowerCase(); + if (!seenHeaders.has(lowerName)) { + targetHeaders.delete(name); + seenHeaders.add(lowerName); } - try { - return await this.fetch.call(void 0, url, fetchOptions); - } finally { - clearTimeout(timeout); + if (value === null) { + targetHeaders.delete(name); + nullHeaders.add(lowerName); + } else { + targetHeaders.append(name, value); + nullHeaders.delete(lowerName); } } - async shouldRetry(response) { - const shouldRetryHeader = response.headers.get("x-should-retry"); - if (shouldRetryHeader === "true") - return true; - if (shouldRetryHeader === "false") - return false; - if (response.status === 408) - return true; - if (response.status === 409) - return true; - if (response.status === 429) - return true; - if (response.status >= 500) - return true; - return false; + } + return { [brand_privateNullableHeaders3]: true, values: targetHeaders, nulls: nullHeaders }; +}; + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/utils/path.mjs +function encodeURIPath3(str) { + return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); +} +var EMPTY3 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); +var createPathTagFunction3 = (pathEncoder = encodeURIPath3) => function path7(statics, ...params) { + if (statics.length === 1) + return statics[0]; + let postPath = false; + const invalidSegments = []; + const path8 = statics.reduce((previousValue, currentValue, index) => { + if (/[?#]/.test(currentValue)) { + postPath = true; } - async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { - let timeoutMillis; - const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms"); - if (retryAfterMillisHeader) { - const timeoutMs = parseFloat(retryAfterMillisHeader); - if (!Number.isNaN(timeoutMs)) { - timeoutMillis = timeoutMs; - } - } - const retryAfterHeader = responseHeaders?.get("retry-after"); - if (retryAfterHeader && !timeoutMillis) { - const timeoutSeconds = parseFloat(retryAfterHeader); - if (!Number.isNaN(timeoutSeconds)) { - timeoutMillis = timeoutSeconds * 1e3; - } else { - timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); - } - } - if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1e3)) { - const maxRetries = options.maxRetries ?? this.maxRetries; - timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); - } - await sleep2(timeoutMillis); - return this.makeRequest(options, retriesRemaining - 1, requestLogID); + const value = params[index]; + let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value); + if (index !== params.length && (value == null || typeof value === "object" && // handle values from other realms + value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY3) ?? EMPTY3)?.toString)) { + encoded = value + ""; + invalidSegments.push({ + start: previousValue.length + currentValue.length, + length: encoded.length, + error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter` + }); } - calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { - const initialRetryDelay = 0.5; - const maxRetryDelay = 8; - const numRetries = maxRetries - retriesRemaining; - const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); - const jitter = 1 - Math.random() * 0.25; - return sleepSeconds * jitter * 1e3; + return previousValue + currentValue + (index === params.length ? "" : encoded); + }, ""); + const pathOnly = path8.split(/[?#]/, 1)[0]; + const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; + let match; + while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) { + invalidSegments.push({ + start: match.index, + length: match[0].length, + error: `Value "${match[0]}" can't be safely passed as a path parameter` + }); + } + invalidSegments.sort((a, b) => a.start - b.start); + if (invalidSegments.length > 0) { + let lastEnd = 0; + const underline = invalidSegments.reduce((acc, segment) => { + const spaces = " ".repeat(segment.start - lastEnd); + const arrows = "^".repeat(segment.length); + lastEnd = segment.start + segment.length; + return acc + spaces + arrows; + }, ""); + throw new GitLabError(`Path parameters result in path with invalid segments: +${invalidSegments.map((e) => e.error).join("\n")} +${path8} +${underline}`); + } + return path8; +}; +var path3 = /* @__PURE__ */ createPathTagFunction3(encodeURIPath3); + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/resources/projects/merge-requests/notes/notes.mjs +var BaseNotes2 = /* @__PURE__ */ (() => { + class BaseNotes13 extends APIResource3 { + /** + * Create a new merge request note + * + * @example + * ```ts + * const apiEntitiesNote = + * await client.projects.mergeRequests.notes.create(0, { + * id: 'id', + * body: 'body', + * }); + * ``` + */ + create(noteableID, params, options) { + const { id, ...body } = params; + return this._client.post(path3`/projects/${id}/merge_requests/${noteableID}/notes`, { body, ...options }); } - async buildRequest(inputOptions, { retryCount = 0 } = {}) { - const options = { ...inputOptions }; - const { method, path: path7, query, defaultBaseURL } = options; - const url = this.buildURL(path7, query, defaultBaseURL); - if ("timeout" in options) - validatePositiveInteger2("timeout", options.timeout); - options.timeout = options.timeout ?? this.timeout; - const { bodyHeaders, body } = this.buildBody({ options }); - const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); - const req = { - method, - headers: reqHeaders, - ...options.signal && { signal: options.signal }, - ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" }, - ...body && { body }, - ...this.fetchOptions ?? {}, - ...options.fetchOptions ?? {} - }; - return { req, url, timeout: options.timeout }; + /** + * Get a single merge request note + * + * @example + * ```ts + * const apiEntitiesNote = + * await client.projects.mergeRequests.notes.retrieve(0, { + * id: 'id', + * noteable_id: 0, + * }); + * ``` + */ + retrieve(noteID, params, options) { + const { id, noteable_id } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${noteable_id}/notes/${noteID}`, options); } - async buildHeaders({ options, method, bodyHeaders, retryCount }) { - let idempotencyHeaders = {}; - if (this.idempotencyHeader && method !== "get") { - if (!options.idempotencyKey) - options.idempotencyKey = this.defaultIdempotencyKey(); - idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; - } - const headers = buildHeaders2([ - idempotencyHeaders, - { - Accept: "application/json", - "User-Agent": this.getUserAgent(), - "X-Stainless-Retry-Count": String(retryCount), - ...options.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options.timeout / 1e3)) } : {}, - ...getPlatformHeaders2() - }, - await this.authHeaders(options), - this._options.defaultHeaders, - bodyHeaders, - options.headers - ]); - this.validateHeaders(headers); - return headers.values; + /** + * Update an existing merge request note + * + * @example + * ```ts + * const apiEntitiesNote = + * await client.projects.mergeRequests.notes.update(0, { + * id: 'id', + * noteable_id: 0, + * }); + * ``` + */ + update(noteID, params, options) { + const { id, noteable_id, ...body } = params; + return this._client.put(path3`/projects/${id}/merge_requests/${noteable_id}/notes/${noteID}`, { + body, + ...options + }); } - _makeAbort(controller) { - return () => controller.abort(); + /** + * Get a list of merge request notes + * + * @example + * ```ts + * const apiEntitiesNote = + * await client.projects.mergeRequests.notes.list(0, { + * id: 'id', + * }); + * ``` + */ + list(noteableID, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${noteableID}/notes`, { query, ...options }); } - buildBody({ options: { body, headers: rawHeaders } }) { - if (!body) { - return { bodyHeaders: void 0, body: void 0 }; - } - const headers = buildHeaders2([rawHeaders]); - if ( - // Pass raw type verbatim - ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && // Preserve legacy string encoding behavior for now - headers.values.has("content-type") || // `Blob` is superset of `File` - globalThis.Blob && body instanceof globalThis.Blob || // `FormData` -> `multipart/form-data` - body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded` - body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`) - globalThis.ReadableStream && body instanceof globalThis.ReadableStream - ) { - return { bodyHeaders: void 0, body }; - } else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) { - return { bodyHeaders: void 0, body: ReadableStreamFrom2(body) }; - } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") { - return { - bodyHeaders: { "content-type": "application/x-www-form-urlencoded" }, - body: this.stringifyQuery(body) - }; - } else { - return __classPrivateFieldGet2(this, _BaseGitLab_encoder, "f").call(this, { body, headers }); - } + /** + * Delete a merge request note + * + * @example + * ```ts + * const apiEntitiesNote = + * await client.projects.mergeRequests.notes.delete(0, { + * id: 'id', + * noteable_id: 0, + * }); + * ``` + */ + delete(noteID, params, options) { + const { id, noteable_id } = params; + return this._client.delete(path3`/projects/${id}/merge_requests/${noteable_id}/notes/${noteID}`, options); } } - _BaseGitLab_encoder = /* @__PURE__ */ new WeakMap(), _BaseGitLab_instances = /* @__PURE__ */ new WeakSet(), _BaseGitLab_baseURLOverridden = function _BaseGitLab_baseURLOverridden2() { - return this.baseURL !== "https://gitlab.com/api/v4"; - }; - BaseGitLab2.DEFAULT_TIMEOUT = 6e4; - return BaseGitLab2; + BaseNotes13._key = Object.freeze([ + "projects", + "mergeRequests", + "notes" + ]); + return BaseNotes13; })(); -// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/tree-shakable.mjs -function createClient2(options) { - const client = new BaseGitLab(options); - for (const ResourceClass of options.resources) { - const resourceInstance = new ResourceClass(client); - let object = client; - for (const part of ResourceClass._key.slice(0, -1)) { - if (hasOwn2(object, part)) { - object = object[part]; - } else { - Object.defineProperty(object, part, { - value: object = {}, - configurable: true, - enumerable: true, - writable: true - }); - } +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/resources/projects/merge-requests/merge-requests.mjs +var BaseMergeRequests = /* @__PURE__ */ (() => { + class BaseMergeRequests3 extends APIResource3 { + /** + * Create a new merge request. + * + * @example + * ```ts + * const apiEntitiesMergeRequest = + * await client.projects.mergeRequests.create('string', { + * source_branch: 'source_branch', + * target_branch: 'target_branch', + * title: 'title', + * }); + * ``` + */ + create(id, body, options) { + return this._client.post(path3`/projects/${id}/merge_requests`, { body, ...options }); + } + /** + * Shows information about a single merge request. Note: the `changes_count` value + * in the response is a string, not an integer. This is because when an merge + * request has too many changes to display and store, it is capped at 1,000. In + * that case, the API returns the string `"1000+"` for the changes count. + * + * @example + * ```ts + * const apiEntitiesMergeRequest = + * await client.projects.mergeRequests.retrieve(0, { + * id: 'string', + * }); + * ``` + */ + retrieve(mergeRequestIid, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${mergeRequestIid}`, { query, ...options }); + } + /** + * Updates an existing merge request. You can change the target branch, title, or + * even close the merge request. + * + * @example + * ```ts + * const apiEntitiesMergeRequest = + * await client.projects.mergeRequests.update(0, { + * id: 'string', + * }); + * ``` + */ + update(mergeRequestIid, params, options) { + const { id, ...body } = params; + return this._client.put(path3`/projects/${id}/merge_requests/${mergeRequestIid}`, { body, ...options }); } - const name = ResourceClass._key.at(-1); - if (!hasOwn2(object, name)) { - Object.defineProperty(object, name, { - value: resourceInstance, - configurable: true, - enumerable: true, - writable: true - }); - } else { - if (object[name] instanceof APIResource2) { - throw new TypeError(`Resource at ${ResourceClass._key.join(".")} already exists!`); - } else { - object[name] = Object.assign(resourceInstance, object[name]); - } + /** + * Get all merge requests for this project. + * + * @example + * ```ts + * const apiEntitiesMergeRequestBasics = + * await client.projects.mergeRequests.list('string'); + * ``` + */ + list(id, query = {}, options) { + return this._client.get(path3`/projects/${id}/merge_requests`, { query, ...options }); } - } - return client; -} - -// src/compat/gitlab/context.ts -var cachedContext2; -function getGitLabContext() { - if (cachedContext2) { - return cachedContext2; - } - const owner = process.env.CI_PROJECT_NAMESPACE; - const repo = process.env.CI_PROJECT_NAME; - const runURL = process.env.CI_JOB_URL; - const projectID = process.env.CI_PROJECT_ID; - if (!owner || !repo || !runURL || !projectID) { - throw new Error( - "Expected env vars CI_PROJECT_NAMESPACE, CI_PROJECT_NAME, CI_JOB_URL, and CI_PROJECT_ID to be set." - ); - } - const host = process.env.CI_SERVER_URL || "https://gitlab.com"; - const apiURL = process.env.CI_API_V4_URL || `${host}/api/v4`; - const maybePRNumber = parseInt( - process.env.CI_MERGE_REQUEST_IID || process.env.MR_NUMBER || "", - 10 - ); - const defaultBranch = process.env.CI_DEFAULT_BRANCH || null; - const prNumber = Number.isInteger(maybePRNumber) ? maybePRNumber : null; - const refName = process.env.CI_COMMIT_REF_NAME || null; - const sha = process.env.CI_COMMIT_SHA || null; - cachedContext2 = { - provider: "gitlab", - host, - owner, - repo, - urls: { api: apiURL, run: runURL }, - names: { ci: "GitLab CI", pr: "MR", provider: "GitLab" }, - defaultBranch, - prNumber, - projectID, - refName, - sha - }; - logger.debug("GitLab context", cachedContext2); - return cachedContext2; -} - -// src/compat/gitlab/api.ts -var GitLabClient = class { - client; - constructor(token) { - this.client = createClient2({ - apiToken: token, - baseURL: getGitLabContext().urls.api, - resources: [BaseCommits3, BaseMergeRequests, BaseNotes2], - logLevel: "warn", - logger - }); - } - async listComments(prNumber) { - const comments = await this.client.projects.mergeRequests.notes.list(prNumber, { id: getGitLabContext().projectID }).then((data) => Array.isArray(data) ? data : [data]).catch((err) => { - if (err instanceof APIError2 && err.status === 404) { - return []; - } - throw err; - }); - return comments.map((c) => ({ id: c.id, body: c.body ?? "" })); - } - async createComment(prNumber, props) { - const data = await this.client.projects.mergeRequests.notes.create( - prNumber, - { ...props, id: getGitLabContext().projectID } - ); - return { id: data.id, body: data.body }; - } - async updateComment(prNumber, props) { - const data = await this.client.projects.mergeRequests.notes.update( - props.id, - { ...props, id: getGitLabContext().projectID, noteable_id: prNumber } - ); - return { id: data.id, body: data.body }; - } - async getPullRequest(number) { - let mergeRequest = null; - let attempts = 0; - while (attempts++ < 3) { - mergeRequest = await this.client.projects.mergeRequests.retrieve(number, { - id: getGitLabContext().projectID + /** + * Only for administrators and project owners. Deletes the merge request in + * question. + * + * @example + * ```ts + * await client.projects.mergeRequests.delete(0, { + * id: 'string', + * }); + * ``` + */ + delete(mergeRequestIid, params, options) { + const { id } = params; + return this._client.delete(path3`/projects/${id}/merge_requests/${mergeRequestIid}`, { + ...options, + headers: buildHeaders3([{ Accept: "*/*" }, options?.headers]) }); - if (mergeRequest?.diff_refs?.start_sha && mergeRequest?.diff_refs?.head_sha) { - return { - number: mergeRequest.iid, - state: mergeRequest.state === "opened" ? "open" : mergeRequest.state === "locked" ? "closed" : mergeRequest.state, - title: mergeRequest.title, - base_sha: mergeRequest.diff_refs.start_sha, - base_ref: mergeRequest.target_branch, - head_sha: mergeRequest.diff_refs.head_sha, - head_ref: mergeRequest.source_branch, - merge_commit_sha: mergeRequest.merge_commit_sha || mergeRequest.squash_commit_sha || null - }; - } - await new Promise((resolve) => { - setTimeout(() => resolve(), 1e3 * (2 ** attempts + Math.random())); + } + /** + * Adds spent time for this merge_request. + * + * @example + * ```ts + * const apiEntitiesIssuableTimeStats = + * await client.projects.mergeRequests.addSpentTime(0, { + * id: 'string', + * duration: 'duration', + * }); + * ``` + */ + addSpentTime(mergeRequestIid, params, options) { + const { id, ...body } = params; + return this._client.post(path3`/projects/${id}/merge_requests/${mergeRequestIid}/add_spent_time`, { + body, + ...options }); } - logger.warn( - `Failed to find get diff_refs for merge request after ${attempts} attempts`, - { mergeRequestIID: number } - ); - return null; - } - async getPullRequestForCommit(sha) { - const mergeRequests = await this.client.projects.repository.commits.retrieveMergeRequests(sha, { - id: getGitLabContext().projectID - }).then( - (data) => ( - // The OAS claims it's a single object, but the docs claim it's an - // array? Just handle both. - (Array.isArray(data) ? data : [data]).filter( - (c) => c.state !== "closed" && c.state !== "locked" - ) - ) - ).catch((err) => { - if (err instanceof APIError2 && (err.status === 401 || err.status === 403 || err.status === 404)) { - return []; - } - throw err; - }); - if (mergeRequests.length === 0) { - return null; + /** + * Approve a merge request + * + * @example + * ```ts + * const apiEntitiesMergeRequestApprovals = + * await client.projects.mergeRequests.approve(0, { + * id: 'id', + * }); + * ``` + */ + approve(mergeRequestIid, params, options) { + const { id, ...body } = params; + return this._client.post(path3`/projects/${id}/merge_requests/${mergeRequestIid}/approve`, { + body, + ...options + }); } - if (mergeRequests.length > 1) { - logger.warn( - `Multiple merge requests found for commit; only using first.`, - { commit: sha, mergeRequests: mergeRequests.map((c) => c.iid) } - ); + /** + * Cancel merge if "Merge When Pipeline Succeeds" is enabled + * + * @example + * ```ts + * const apiEntitiesMergeRequest = + * await client.projects.mergeRequests.cancelMergeWhenPipelineSucceeds( + * 0, + * { id: 'string' }, + * ); + * ``` + */ + cancelMergeWhenPipelineSucceeds(mergeRequestIid, params, options) { + const { id } = params; + return this._client.post(path3`/projects/${id}/merge_requests/${mergeRequestIid}/cancel_merge_when_pipeline_succeeds`, options); } - const mergeRequestIID = mergeRequests[0].iid; - const mergeRequest = await this.getPullRequest(mergeRequestIID); - return mergeRequest; - } -}; -var cachedClient2; -function getGitLabClient() { - if (cachedClient2 !== void 0) { - return cachedClient2; - } - const token = getInput("GITLAB_TOKEN"); - if (token?.startsWith("$")) { - throw new Error( - `Input GITLAB_TOKEN starts with '$'; expected token to start with 'gl'. Does the CI have access to the variable?` - ); - } - if (token) { - cachedClient2 = new GitLabClient(token); - } else { - logger.info("No GitLab token found in input 'GITLAB_TOKEN'."); - cachedClient2 = null; - } - return cachedClient2; -} - -// src/compat/api.ts -function api(options) { - let client; - switch (getProvider()) { - case "github": { - client = getGitHubClient(); - break; + /** + * Resets the total spent time for this merge_request to 0 seconds. + * + * @example + * ```ts + * const apiEntitiesIssuableTimeStats = + * await client.projects.mergeRequests.resetSpentTime(0, { + * id: 'string', + * }); + * ``` + */ + resetSpentTime(mergeRequestIid, params, options) { + const { id } = params; + return this._client.post(path3`/projects/${id}/merge_requests/${mergeRequestIid}/reset_spent_time`, options); } - case "gitlab": { - client = getGitLabClient(); - break; + /** + * Resets the estimated time for this merge_request to 0 seconds. + * + * @example + * ```ts + * const apiEntitiesIssuableTimeStats = + * await client.projects.mergeRequests.resetTimeEstimate(0, { + * id: 'string', + * }); + * ``` + */ + resetTimeEstimate(mergeRequestIid, params, options) { + const { id } = params; + return this._client.post(path3`/projects/${id}/merge_requests/${mergeRequestIid}/reset_time_estimate`, options); } - } - if (!client) { - if (options?.optional) { - return null; - } else { - throw new Error("Failed to get API client."); + /** + * List approval rules for merge request + * + * @example + * ```ts + * await client.projects.mergeRequests.retrieveApprovalSettings( + * 0, + * { id: 'string' }, + * ); + * ``` + */ + retrieveApprovalSettings(mergeRequestIid, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${mergeRequestIid}/approval_settings`, { + query, + ...options, + headers: buildHeaders3([{ Accept: "*/*" }, options?.headers]) + }); } - } - return client; -} - -// src/compat/context.ts -function ctx() { - switch (getProvider()) { - case "github": { - return getGitHubContext(); + /** + * Get approval state of merge request + * + * @example + * ```ts + * const response = + * await client.projects.mergeRequests.retrieveApprovalState( + * 0, + * { id: 'string' }, + * ); + * ``` + */ + retrieveApprovalState(mergeRequestIid, params, options) { + const { id } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${mergeRequestIid}/approval_state`, options); } - case "gitlab": { - return getGitLabContext(); + /** + * Get all merge requests are blockees for this merge request + * + * @example + * ```ts + * const apiEntitiesMergeRequestDependency = + * await client.projects.mergeRequests.retrieveBlockees(0, { + * id: 'string', + * }); + * ``` + */ + retrieveBlockees(mergeRequestIid, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${mergeRequestIid}/blockees`, { + query, + ...options + }); } - } -} - -// src/compat/output.ts -var crypto = __toESM(require("node:crypto")); -var fs2 = __toESM(require("node:fs")); -function setOutput(name, value) { - if (getProvider() === "gitlab") return; - const stringified = value === null || value === void 0 ? "" : typeof value === "string" ? value : JSON.stringify(value); - const filePath = process.env["GITHUB_OUTPUT"]; - if (filePath && fs2.existsSync(filePath)) { - const delimiter = `ghadelimiter_${crypto.randomUUID()}`; - fs2.appendFileSync( - filePath, - `${name}<<${delimiter} -${stringified} -${delimiter} -`, - "utf-8" - ); - } else { - process.stdout.write(` -::set-output name=${name}::${stringified} -`); - } -} - -// src/compat/index.ts -async function getStainlessAuth() { - const apiKey = getInput("stainless_api_key", { - required: getProvider() === "gitlab" - }); - if (apiKey) { - logger.debug("Authenticating with provided Stainless API key"); - return { - key: apiKey, - expiresAt: null - }; - } - logger.debug("Authenticating with GitHub OIDC"); - const requestUrl = process.env.ACTIONS_ID_TOKEN_REQUEST_URL; - const requestToken = process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN; - if (!requestUrl || !requestToken) { - throw new Error( - `Failed to authenticate with GitHub OIDC. Make sure your workflow has 'id-token: write' permission and that you have the Stainless GitHub App installed: https://www.stainless.com/docs/guides/publish/#install-the-stainless-github-app` - ); - } - try { - const response = await fetch(`${requestUrl}&audience=api.stainless.com`, { - headers: { Authorization: `Bearer ${requestToken}` } - }); - if (!response.ok) { - throw new Error(`HTTP ${response.status}: ${await response.text()}`); + /** + * Shows information about the merge request including its files and changes. + * + * @example + * ```ts + * const response = + * await client.projects.mergeRequests.retrieveChanges(0, { + * id: 'string', + * }); + * ``` + */ + retrieveChanges(mergeRequestIid, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${mergeRequestIid}/changes`, { + query, + ...options + }); } - const data = await response.json(); - if (!data.value) { - throw new Error("No token in OIDC response"); + /** + * Get all the issues that would be closed by merging the provided merge request. + * + * @example + * ```ts + * const response = + * await client.projects.mergeRequests.retrieveClosesIssues( + * 0, + * { id: 'string' }, + * ); + * ``` + */ + retrieveClosesIssues(mergeRequestIid, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${mergeRequestIid}/closes_issues`, { + query, + ...options + }); } - return { - key: data.value, - expiresAt: Date.now() + 300 * 1e3 - }; - } catch (error) { - throw new Error( - `Failed to authenticate with GitHub OIDC. Make sure your workflow has 'id-token: write' permission and that you have the Stainless GitHub App installed: https://www.stainless.com/docs/guides/publish/#install-the-stainless-github-app. Error: ${error}` - ); - } -} - -// src/outcomes.ts -var ASSUME_PENDING_CHECKS_SKIPPED_AFTER_SECS = 60; -var FailRunOn = [ - "never", - "fatal", - "error", - "warning", - "note" -]; -var OutcomeConclusion = [...FailRunOn, "success"]; -function shouldFailRun({ - failRunOn, - outcomes, - baseOutcomes -}) { - const failures = Object.entries(outcomes).flatMap(([language, outcome]) => { - const categorized = categorizeOutcome({ - outcome, - baseOutcome: baseOutcomes?.[language] - }); - if (categorized.isPending) { - return []; + /** + * Get a list of merge request commits. + * + * @example + * ```ts + * const apiEntitiesCommit = + * await client.projects.mergeRequests.retrieveCommits(0, { + * id: 'string', + * }); + * ``` + */ + retrieveCommits(mergeRequestIid, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${mergeRequestIid}/commits`, { + query, + ...options + }); + } + /** + * Get a list of merge request diffs. + * + * @example + * ```ts + * const apiEntitiesDiff = + * await client.projects.mergeRequests.retrieveDiffs(0, { + * id: 'string', + * }); + * ``` + */ + retrieveDiffs(mergeRequestIid, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${mergeRequestIid}/diffs`, { + query, + ...options + }); + } + /** + * Returns the up to date merge-ref HEAD commit + * + * @example + * ```ts + * await client.projects.mergeRequests.retrieveMergeRef(0, { + * id: 'string', + * }); + * ``` + */ + retrieveMergeRef(mergeRequestIid, params, options) { + const { id } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${mergeRequestIid}/merge_ref`, { + ...options, + headers: buildHeaders3([{ Accept: "*/*" }, options?.headers]) + }); } - const { severity, isRegression, description } = categorized; - const didFail = isRegression !== false && severity && OutcomeConclusion.indexOf(severity) <= OutcomeConclusion.indexOf(failRunOn); - return didFail ? [ - { - language, - reason: getReason({ - description, - isRegression - }) - } - ] : []; - }); - if (failures.length > 0) { - logger.warn("The following languages did not build successfully:"); - for (const { language, reason } of failures) { - logger.warn(` ${language}: ${reason}`); + /** + * Get a list of merge request participants. + * + * @example + * ```ts + * const apiEntitiesUserBasic = + * await client.projects.mergeRequests.retrieveParticipants( + * 0, + * { id: 'string' }, + * ); + * ``` + */ + retrieveParticipants(mergeRequestIid, params, options) { + const { id } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${mergeRequestIid}/participants`, options); } - return false; - } - return true; -} -function categorizeOutcome({ - outcome, - baseOutcome -}) { - const baseConclusion = baseOutcome?.commit?.conclusion; - const headConclusion = outcome.commit?.conclusion; - if (!headConclusion || baseOutcome && !baseConclusion) { - return { isPending: true }; - } - const baseChecks = baseOutcome && baseOutcome.commit?.commit ? getChecks(baseOutcome) : {}; - const headChecks = outcome.commit?.commit ? getChecks(outcome) : {}; - if ([...Object.values(headChecks), ...Object.values(baseChecks)].some( - (check) => check && check.status !== "completed" - )) { - return { isPending: true }; - } - const newDiagnostics = sortDiagnostics( - baseOutcome ? getNewDiagnostics(outcome.diagnostics, baseOutcome.diagnostics) : outcome.diagnostics - ); - const conclusions = { - fatal: [ - "fatal", - "payment_required", - "timed_out", - "upstream_merge_conflict", - "version_bump" - ], - conflict: ["merge_conflict"], - diagnostic: ["error", "warning", "note"], - success: ["success", "noop", "cancelled"] - }; - const checks = getNewChecks(headChecks, baseChecks); - const checkFailures = CheckType.filter( - (checkType) => checks[checkType] && checks[checkType].status === "completed" && ["failure", "timed_out"].includes(checks[checkType].completed.conclusion) - ); - if (headConclusion === "timed_out" || baseConclusion === "timed_out") { - return { - isPending: false, - conclusion: "timed_out", - severity: "fatal", - description: "timed out before completion", - isRegression: null - }; - } - if (conclusions.fatal.includes(headConclusion)) { - return { - isPending: false, - conclusion: "fatal", - severity: "fatal", - description: `had a "${headConclusion}" conclusion, and no code was generated`, - isRegression: baseConclusion ? conclusions.fatal.includes(baseConclusion) ? false : true : null - }; - } - if (baseConclusion && conclusions.fatal.includes(baseConclusion)) { - return { - isPending: false, - conclusion: headConclusion, - severity: null, - description: `had a "${baseOutcome?.commit?.conclusion}" conclusion in the base build, which improved to "${headConclusion}"`, - isRegression: false - }; - } - if (conclusions.diagnostic.includes(headConclusion) || newDiagnostics.length > 0 || checkFailures.length > 0) { - const categoryOutcome = conclusions.diagnostic.includes(headConclusion) ? { - severity: headConclusion, - description: `had at least one "${headConclusion}" diagnostic`, - isRegression: baseConclusion ? conclusions.success.includes(baseConclusion) || conclusions.diagnostic.indexOf(headConclusion) < conclusions.diagnostic.indexOf(baseConclusion) ? true : false : null, - rank: 1 - } : null; - const diagnosticLevelOutcome = newDiagnostics.length > 0 ? { - severity: newDiagnostics[0].level, - description: `had at least one ${baseOutcome ? "new " : ""}${newDiagnostics[0].level} diagnostic`, - isRegression: baseOutcome ? true : null, - rank: 2 - } : null; - let checkFailureOutcome; - for (const { step, severity } of [ - { step: "build", severity: "error" }, - { step: "lint", severity: "warning" }, - { step: "test", severity: "warning" } - ]) { - if (checkFailures.includes(step)) { - checkFailureOutcome = { - severity, - description: `had a failure in the ${step} CI job`, - isRegression: baseChecks ? true : null, - rank: 3 - }; - break; - } + /** + * Get the raw diffs of a merge request that can used programmatically. + * + * @example + * ```ts + * await client.projects.mergeRequests.retrieveRawDiffs(0, { + * id: 'string', + * }); + * ``` + */ + retrieveRawDiffs(mergeRequestIid, params, options) { + const { id } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${mergeRequestIid}/raw_diffs`, { + ...options, + headers: buildHeaders3([{ Accept: "*/*" }, options?.headers]) + }); } - const worstOutcome = [ - categoryOutcome, - diagnosticLevelOutcome, - checkFailureOutcome - ].filter((r) => r !== null).sort( - (a, b) => ( - // sort by regression status then severity then rank - (!(a.severity === "fatal" || b.severity === "fatal") ? [true, null, false].indexOf(a.isRegression) - [true, null, false].indexOf(b.isRegression) : 0) || conclusions.diagnostic.indexOf(a.severity) - conclusions.diagnostic.indexOf(b.severity) || a.rank - b.rank - ) - )[0]; - return { - isPending: false, - conclusion: worstOutcome.severity, - ...worstOutcome - }; - } - if (conclusions.conflict.includes(headConclusion)) { - return { - isPending: false, - conclusion: "merge_conflict", - severity: baseConclusion !== "merge_conflict" ? "warning" : null, - description: "resulted in a merge conflict between your custom code and the newly generated changes", - isRegression: baseConclusion ? baseConclusion !== "merge_conflict" ? true : false : null - }; - } - return { - isPending: false, - conclusion: headConclusion, - severity: null, - description: headConclusion === "success" ? "was successful" : `had a conclusion of ${headConclusion}`, - isRegression: null - }; -} -function getReason({ - description, - isRegression -}) { - return `Your SDK build ${description}${isRegression === true ? ", which is a regression from the base state" : isRegression === false ? ", but this did not represent a regression" : ""}.`; -} -var DiagnosticLevel = ["fatal", "error", "warning", "note"]; -function countDiagnosticLevels(diagnostics) { - return diagnostics.reduce( - (counts, diag) => { - counts[diag.level] = (counts[diag.level] || 0) + 1; - return counts; - }, - { - fatal: 0, - error: 0, - warning: 0, - note: 0 + /** + * Get all the related issues from title, description, commits, comments and + * discussions of the merge request. + * + * @example + * ```ts + * await client.projects.mergeRequests.retrieveRelatedIssues( + * 0, + * { id: 'string' }, + * ); + * ``` + */ + retrieveRelatedIssues(mergeRequestIid, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${mergeRequestIid}/related_issues`, { + query, + ...options, + headers: buildHeaders3([{ Accept: "*/*" }, options?.headers]) + }); } - ); -} -function getNewDiagnostics(diagnostics, baseDiagnostics) { - if (!baseDiagnostics) { - return diagnostics; - } - return diagnostics.filter( - (d) => !baseDiagnostics.some( - (bd) => bd.code === d.code && bd.message === d.message && bd.config_ref === d.config_ref && bd.oas_ref === d.oas_ref - ) - ); -} -function sortDiagnostics(diagnostics) { - return diagnostics.sort( - (a, b) => DiagnosticLevel.indexOf(a.level) - DiagnosticLevel.indexOf(b.level) - ); -} -var CheckType = ["build", "lint", "test"]; -function getChecks(outcome) { - const results = {}; - const commitCompletedMoreThanXSecsAgo = outcome.commit ? (/* @__PURE__ */ new Date()).getTime() - new Date(outcome.commit.completed_at).getTime() > ASSUME_PENDING_CHECKS_SKIPPED_AFTER_SECS * 1e3 : false; - for (const checkType of CheckType) { - if (outcome[checkType]?.status === "not_started" && commitCompletedMoreThanXSecsAgo) { - outcome[checkType] = { - status: "completed", - conclusion: "skipped", - completed: { - conclusion: "skipped", - url: null - }, - url: null - }; + /** + * Get a list of merge request reviewers. + * + * @example + * ```ts + * const response = + * await client.projects.mergeRequests.retrieveReviewers(0, { + * id: 'string', + * }); + * ``` + */ + retrieveReviewers(mergeRequestIid, params, options) { + const { id } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${mergeRequestIid}/reviewers`, options); + } + /** + * Get time tracking stats + * + * @example + * ```ts + * const apiEntitiesIssuableTimeStats = + * await client.projects.mergeRequests.retrieveTimeStats(0, { + * id: 'string', + * }); + * ``` + */ + retrieveTimeStats(mergeRequestIid, params, options) { + const { id } = params; + return this._client.get(path3`/projects/${id}/merge_requests/${mergeRequestIid}/time_stats`, options); } - results[checkType] = outcome[checkType] || null; - } - return results; -} -function getNewChecks(headChecks, baseChecks) { - const result = {}; - for (const checkType of CheckType) { - const headCheck = headChecks[checkType]; - const baseCheck = baseChecks ? baseChecks[checkType] : null; - if (headCheck) { - const baseConclusion = baseCheck?.status === "completed" && baseCheck.conclusion; - const conclusion = headCheck.status === "completed" && headCheck.conclusion; - if (!baseConclusion || baseConclusion !== conclusion) { - result[checkType] = headCheck; - } + /** + * Set status of an external status check + * + * @example + * ```ts + * const response = + * await client.projects.mergeRequests.statusCheckResponses( + * 1, + * { + * id: '1', + * external_status_check_id: 1, + * sha: '5957a570eee0ac4580ec027fb874ad7514d1e576', + * status: 'passed', + * }, + * ); + * ``` + */ + statusCheckResponses(mergeRequestIid, params, options) { + const { id, ...body } = params; + return this._client.post(path3`/projects/${id}/merge_requests/${mergeRequestIid}/status_check_responses`, { + body, + ...options + }); } - } - return result; -} - -// src/preview.run.ts -var fs5 = __toESM(require("node:fs")); - -// src/commitMessage.ts -var CONVENTIONAL_COMMIT_REGEX = new RegExp( - /^(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test)(\(.*\))?(!?): .*$/m -); -function makeCommitMessageConventional(message) { - if (message && !CONVENTIONAL_COMMIT_REGEX.test(message)) { - logger.warn( - `Commit message "${message}" is not in Conventional Commits format: https://www.conventionalcommits.org/en/v1.0.0/. Prepending "feat:" and using anyway.` - ); - return `feat: ${message}`; - } - return message; -} - -// src/markdown.ts -var import_ts_dedent = __toESM(require_dist()); -var Symbol2 = { - Bulb: "\u{1F4A1}", - Construction: "\u{1F6A7}", - Exclamation: "\u2757", - Eyes: "\u{1F440}", - GreenSquare: "\u{1F7E9}", - HeavyAsterisk: "\u2731", - HourglassFlowingSand: "\u23F3", - MiddleDot: "\xB7", - RedSquare: "\u{1F7E5}", - RightwardsArrow: "\u2192", - Skipped: "\u23ED\uFE0F", - SpeechBalloon: "\u{1F4AC}", - Warning: "\u26A0\uFE0F", - WhiteCheckMark: "\u2705", - WhiteLargeSquare: "\u2B1C", - Zap: "\u26A1" -}; -var Bold = (content) => `${content}`; -var CodeInline = (content) => `${content}`; -var Comment = (content) => ``; -var Italic = (content) => `${content}`; -function Dedent(templ, ...args) { - return (0, import_ts_dedent.dedent)(templ, ...args).trim().replaceAll(/\n\s*\n/gi, "\n\n"); -} -var Blockquote = (content) => Dedent` -
- - ${content} - -
- `; -var CodeBlock = (props) => { - const delimiter = "```"; - const content = typeof props === "string" ? props : props.content; - const language = typeof props === "string" ? "" : props.language; - return Dedent` - ${delimiter}${language} - ${content} - ${delimiter} - `; -}; -var Details = ({ - summary, - body, - indent = true, - open = false -}) => { - return Dedent` - - ${summary} - - ${indent ? Blockquote(body) : body} - - - `; -}; -var Heading = (content) => `

${content}

`; -var Link = ({ text, href }) => `${text}`; -var Rule = () => `
`; - -// src/comment.ts -var COMMENT_TITLE = Heading( - `${Symbol2.HeavyAsterisk} Stainless preview builds` -); -var COMMENT_FOOTER_DIVIDER = Comment("stainless-preview-footer"); -function printComment({ - noChanges, - orgName, - projectName, - branch, - commitMessage, - targetCommitMessages, - pendingAiCommitMessages, - baseOutcomes, - outcomes -}) { - const Blocks4 = (() => { - if (noChanges) { - return "No changes were made to the SDKs."; + /** + * Subscribe to a resource + * + * @example + * ```ts + * const apiEntitiesMergeRequest = + * await client.projects.mergeRequests.subscribe( + * 'subscribable_id', + * { id: 'id' }, + * ); + * ``` + */ + subscribe(subscribableID, params, options) { + const { id } = params; + return this._client.post(path3`/projects/${id}/merge_requests/${subscribableID}/subscribe`, options); } - const canEdit = !!baseOutcomes; - return [ - Dedent` - This ${ctx().names.pr} will update the ${CodeInline( - projectName - )} SDKs with the following commit ${targetCommitMessages ? "messages" : "message"}. - `, - targetCommitMessages ? CommitMessagesSection({ - targets: Object.keys(outcomes).sort(), - pendingAiCommitMessages, - targetCommitMessages, - commitMessage - }) : CodeBlock(commitMessage), - !canEdit ? null : targetCommitMessages ? "Edit this comment to update them. They will appear in their respective SDK's changelogs." : "Edit this comment to update it. It will appear in the SDK's changelogs.", - Results({ orgName, projectName, branch, outcomes, baseOutcomes }) - ].filter((f) => f !== null).join(` - -`); - })(); - const dateString = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").replace(/\.\d+Z$/, " UTC"); - const fullComment = Dedent` - ${COMMENT_TITLE} - - ${Blocks4} - - ${Rule()} - - ${COMMENT_FOOTER_DIVIDER} - - ${Italic( - `This comment is auto-generated by ${ctx().names.ci} and is automatically kept up to date as you push.
If you push custom code to the preview branch, ${Link({ - text: `re-run this workflow`, - href: ctx().urls.run - })} to update the comment.
Last updated: ${dateString}` - )} - `; - return fullComment; -} -function CommitMessagesSection({ - targets, - pendingAiCommitMessages, - targetCommitMessages, - commitMessage -}) { - return targets.map((target) => { - const statusText = pendingAiCommitMessages?.has(target) ? `${Symbol2.HourglassFlowingSand} (generating...)` : ""; - const message = targetCommitMessages[target] ?? commitMessage; - return Dedent` - **${target}** - ${statusText}${CodeBlock(message)} - `; - }).join("\n"); -} -var DiagnosticIcon = { - fatal: Symbol2.Exclamation, - error: Symbol2.Exclamation, - warning: Symbol2.Warning, - note: Symbol2.Bulb -}; -function Results({ - orgName, - projectName, - branch, - outcomes, - baseOutcomes -}) { - const results = []; - let hasPending = false; - Object.entries(outcomes).forEach(([lang, head]) => { - const base = baseOutcomes?.[lang]; - hasPending ||= categorizeOutcome({ - outcome: head, - baseOutcome: base - }).isPending ?? false; - const result = Result({ - orgName, - projectName, - branch, - lang, - head, - base - }); - if (result) { - results.push(result); + /** + * Sets an estimated time of work for this merge_request. + * + * @example + * ```ts + * const apiEntitiesIssuableTimeStats = + * await client.projects.mergeRequests.timeEstimate(0, { + * id: 'string', + * duration: '3h30m', + * }); + * ``` + */ + timeEstimate(mergeRequestIid, params, options) { + const { id, ...body } = params; + return this._client.post(path3`/projects/${id}/merge_requests/${mergeRequestIid}/time_estimate`, { + body, + ...options + }); } - }); - if (hasPending) { - results.push( - Dedent` - ${Symbol2.HourglassFlowingSand} These are partial results; builds are still running. - ` - ); - } - return results.join("\n\n"); -} -function Result({ - orgName, - projectName, - branch, - lang, - head, - base -}) { - const categorized = categorizeOutcome({ - outcome: head, - baseOutcome: base - }); - const { ResultIcon, Description } = (() => { - if (categorized.isPending) { - return { - ResultIcon: Symbol2.HourglassFlowingSand, - Description: "" - }; + /** + * Create a to-do item on an issuable + * + * @example + * ```ts + * const apiEntitiesTodo = + * await client.projects.mergeRequests.todo(0, { id: 'id' }); + * ``` + */ + todo(mergeRequestIid, params, options) { + const { id } = params; + return this._client.post(path3`/projects/${id}/merge_requests/${mergeRequestIid}/todo`, options); } - const { severity, conclusion, isRegression, description } = categorized; - const reason = getReason({ - description, - isRegression - }); - if (isRegression !== false && severity === "fatal") { - return { - ResultIcon: Symbol2.Exclamation, - Description: Italic(reason) - }; + /** + * Remove an approval from a merge request + * + * @example + * ```ts + * const apiEntitiesMergeRequestApprovals = + * await client.projects.mergeRequests.unapprove(0, { + * id: 'id', + * }); + * ``` + */ + unapprove(mergeRequestIid, params, options) { + const { id } = params; + return this._client.post(path3`/projects/${id}/merge_requests/${mergeRequestIid}/unapprove`, options); } - if (isRegression !== false && conclusion === "merge_conflict") { - return { - ResultIcon: Symbol2.Zap, - Description: [ - Italic(reason), - Italic( - `You don't need to resolve this conflict right now, but you will need to resolve it for your changes to be released to your users. Read more about why this happened ${Link({ - text: "here", - href: "https://www.stainless.com/docs/guides/add-custom-code" - })}.` - ) - ].join("\n") - }; + /** + * Unsubscribe from a resource + * + * @example + * ```ts + * const apiEntitiesMergeRequest = + * await client.projects.mergeRequests.unsubscribe( + * 'subscribable_id', + * { id: 'id' }, + * ); + * ``` + */ + unsubscribe(subscribableID, params, options) { + const { id } = params; + return this._client.post(path3`/projects/${id}/merge_requests/${subscribableID}/unsubscribe`, options); } - if (isRegression !== false && severity !== "note" && severity !== null) { - return { - ResultIcon: Symbol2.Warning, - Description: Italic(reason) - }; + /** + * Accept and merge changes submitted with the merge request using this API. + * + * @example + * ```ts + * const apiEntitiesMergeRequest = + * await client.projects.mergeRequests.updateMerge(0, { + * id: 'string', + * }); + * ``` + */ + updateMerge(mergeRequestIid, params, options) { + const { id, ...body } = params; + return this._client.put(path3`/projects/${id}/merge_requests/${mergeRequestIid}/merge`, { + body, + ...options + }); } - return { - ResultIcon: severity === "fatal" ? Symbol2.Construction : Symbol2.WhiteCheckMark, - Description: Italic(reason) - }; - })(); - return Details({ - summary: [ - ResultIcon, - Bold(`${projectName}-${lang}`), - [ - Link({ - text: "studio", - href: `https://app.stainless.com/${orgName}/${projectName}/studio?language=${lang}&branch=${encodeURIComponent(branch)}` - }), - GitHubLink(head), - base ? CompareLink(base, head) : null, - MergeConflictLink(head) - ].filter((link) => link !== null).join(` ${Symbol2.MiddleDot} `) - ].join(" "), - body: [ - Description, - StatusLine(base, head), - InstallationDetails(head, lang), - base ? DiagnosticsDetails(head, base) : null - ].filter((value) => Boolean(value)).join("\n"), - open: !categorized.isPending && categorized.isRegression !== false && categorized.severity !== "note" && categorized.severity !== null - }); -} -function StatusLine(base, head) { - return [ - StatusStep(base, head, "generate"), - StatusStep(base, head, "build"), - StatusStep(base, head, "lint"), - StatusStep(base, head, "test") - ].filter((value) => Boolean(value)).join(` ${Symbol2.RightwardsArrow} `); -} -function StatusStep(base, head, step) { - let baseStatus = base ? StatusSymbol(base, step) : null; - let headStatus = StatusSymbol(head, step); - if (!headStatus) { - return null; - } - if (baseStatus === Symbol2.HourglassFlowingSand || headStatus === Symbol2.HourglassFlowingSand) { - baseStatus = Symbol2.HourglassFlowingSand; - headStatus = Symbol2.HourglassFlowingSand; - } - const headText = CodeInline(`${step} ${headStatus}`); - const headURL = StatusURL(head, step); - const headLink = headURL ? Link({ text: headText, href: headURL }) : headText; - if (!baseStatus || baseStatus === headStatus) { - return headLink; - } - const baseText = CodeInline(`${step} ${baseStatus}`); - const baseURL = StatusURL(base, step); - const baseLink = baseURL ? Link({ text: baseText, href: baseURL }) : baseText; - return `${headLink} (prev: ${baseLink})`; -} -function StatusSymbol(outcome, step) { - if (!outcome.commit?.completed?.commit) { - return null; - } - if (step === "generate") { - switch (outcome.commit.completed.conclusion) { - case "fatal": - case "error": - case "cancelled": - return Symbol2.Exclamation; - case "merge_conflict": - return Symbol2.Zap; - case "upstream_merge_conflict": - case "warning": - return Symbol2.Warning; - default: - return Symbol2.WhiteCheckMark; + /** + * Automatically rebase the `source_branch` of the merge request against its + * `target_branch`. This feature was added in GitLab 11.6 + * + * @example + * ```ts + * await client.projects.mergeRequests.updateRebase(0, { + * id: 'string', + * }); + * ``` + */ + updateRebase(mergeRequestIid, params, options) { + const { id, ...body } = params; + return this._client.put(path3`/projects/${id}/merge_requests/${mergeRequestIid}/rebase`, { + body, + ...options, + headers: buildHeaders3([{ Accept: "*/*" }, options?.headers]) + }); + } + /** + * Clear all approvals of merge request. This feature was added in GitLab 15.4 + * + * @example + * ```ts + * await client.projects.mergeRequests.updateResetApprovals( + * 0, + * { id: 'id' }, + * ); + * ``` + */ + updateResetApprovals(mergeRequestIid, params, options) { + const { id } = params; + return this._client.put(path3`/projects/${id}/merge_requests/${mergeRequestIid}/reset_approvals`, { + ...options, + headers: buildHeaders3([{ Accept: "*/*" }, options?.headers]) + }); } } - const stepData = outcome[step]; - if (!stepData) { - return null; - } - if (stepData.status === "completed") { - return stepData.completed.conclusion === "success" ? Symbol2.WhiteCheckMark : stepData.completed.conclusion === "skipped" ? Symbol2.Skipped : Symbol2.Exclamation; + BaseMergeRequests3._key = Object.freeze([ + "projects", + "mergeRequests" + ]); + return BaseMergeRequests3; +})(); + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/shims.mjs +function getDefaultFetch3() { + if (typeof fetch !== "undefined") { + return fetch; } - return Symbol2.HourglassFlowingSand; + throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new GitLab({ fetch })` or polyfill the global, `globalThis.fetch = fetch`"); } -function StatusURL(outcome, step) { - if (step === "generate" || !outcome[step]) { - return null; - } - if (outcome[step].status !== "not_started") { - return outcome[step].url; +function makeReadableStream3(...args) { + const ReadableStream = globalThis.ReadableStream; + if (typeof ReadableStream === "undefined") { + throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`"); } + return new ReadableStream(...args); } -function GitHubLink(outcome) { - if (!outcome.commit?.completed?.commit) return null; - const { - repo: { owner, name, branch } - } = outcome.commit.completed.commit; - return Link({ - text: "code", - // This is a staging repo, so it's always GitHub. - href: `https://github.com/${owner}/${name}/tree/${encodeURIComponent(branch)}` +function ReadableStreamFrom3(iterable) { + let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); + return makeReadableStream3({ + start() { + }, + async pull(controller) { + const { done, value } = await iter.next(); + if (done) { + controller.close(); + } else { + controller.enqueue(value); + } + }, + async cancel() { + await iter.return?.(); + } }); } -function CompareLink(base, head) { - if (!base.commit?.completed?.commit || !head.commit?.completed?.commit) { - return null; +async function CancelReadableStream3(stream) { + if (stream === null || typeof stream !== "object") + return; + if (stream[Symbol.asyncIterator]) { + await stream[Symbol.asyncIterator]().return?.(); + return; } - const { repo } = head.commit.completed.commit; - const baseBranch = base.commit.completed.commit.repo.branch; - const headBranch = head.commit.completed.commit.repo.branch; - const compareURL = `https://github.com/${repo.owner}/${repo.name}/compare/${encodeURIComponent(baseBranch)}..${encodeURIComponent(headBranch)}`; - return Link({ text: "diff", href: compareURL }); + const reader = stream.getReader(); + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; } -function MergeConflictLink(outcome) { - if (!outcome.commit?.completed?.merge_conflict_pr) return null; - const { - repo: { owner, name }, - number - } = outcome.commit.completed.merge_conflict_pr; - return Link({ - text: "conflict", - href: `https://github.com/${owner}/${name}/pull/${number}` - }); + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/uploads.mjs +var checkFileSupport3 = () => { + if (typeof File === "undefined") { + const { process: process7 } = globalThis; + const isOldNode = typeof process7?.versions?.node === "string" && parseInt(process7.versions.node.split(".")) < 20; + throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : "")); + } +}; +function makeFile3(fileBits, fileName, options) { + checkFileSupport3(); + return new File(fileBits, fileName ?? "unknown_file", options); } -function DiagnosticsDetails(head, base) { - if (!base.diagnostics || !head.diagnostics) return null; - const newDiagnostics = getNewDiagnostics(head.diagnostics, base.diagnostics); - if (newDiagnostics.length === 0) return null; - const levelCounts = countDiagnosticLevels(newDiagnostics); - const diagnosticCounts = Object.entries(levelCounts).filter(([, count]) => count > 0).map(([level, count]) => `${count} ${level}`); - const diagnosticList = sortDiagnostics(newDiagnostics).slice(0, 10).map((d) => `${DiagnosticIcon[d.level]} ${Bold(d.code)}: ${d.message}`).filter(Boolean); - const tableRows = diagnosticList.map((diagnostic) => ` -${diagnostic} -`).join("\n"); - const tableContent = ` -${tableRows} -
`; - return Details({ - summary: `New diagnostics (${diagnosticCounts.join(", ")})`, - body: tableContent, - indent: false - }); +function getName3(value) { + return (typeof value === "object" && value !== null && ("name" in value && value.name && String(value.name) || "url" in value && value.url && String(value.url) || "filename" in value && value.filename && String(value.filename) || "path" in value && value.path && String(value.path)) || "").split(/[\\/]/).pop() || void 0; } -function InstallationDetails(head, lang) { - let githubGoURL = null; - let installation = null; - if (head.commit?.completed.commit) { - const { repo, sha } = head.commit.completed.commit; - githubGoURL = `github.com/${repo.owner}/${repo.name}@${sha}`; - } - switch (lang) { - case "typescript": - case "node": { - if (head.install_url) { - installation = `npm install ${head.install_url}`; +var isAsyncIterable3 = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function"; +var multipartFormRequestOptions = async (opts, fetch2) => { + return { ...opts, body: await createForm(opts.body, fetch2) }; +}; +var supportsFormDataMap = /* @__PURE__ */ new WeakMap(); +function supportsFormData(fetchObject) { + const fetch2 = typeof fetchObject === "function" ? fetchObject : fetchObject.fetch; + const cached = supportsFormDataMap.get(fetch2); + if (cached) + return cached; + const promise = (async () => { + try { + const FetchResponse = "Response" in fetch2 ? fetch2.Response : (await fetch2("data:,")).constructor; + const data = new FormData(); + if (data.toString() === await new FetchResponse(data).text()) { + return false; } - break; + return true; + } catch { + return true; + } + })(); + supportsFormDataMap.set(fetch2, promise); + return promise; +} +var createForm = async (body, fetch2) => { + if (!await supportsFormData(fetch2)) { + throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class."); + } + const form = new FormData(); + await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value))); + return form; +}; +var isNamedBlob = (value) => value instanceof Blob && "name" in value; +var addFormValue = async (form, key, value) => { + if (value === void 0) + return; + if (value == null) { + throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`); + } + if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { + form.append(key, String(value)); + } else if (value instanceof Response) { + form.append(key, makeFile3([await value.blob()], getName3(value))); + } else if (isAsyncIterable3(value)) { + form.append(key, makeFile3([await new Response(ReadableStreamFrom3(value)).blob()], getName3(value))); + } else if (isNamedBlob(value)) { + form.append(key, value, getName3(value)); + } else if (Array.isArray(value)) { + await Promise.all(value.map((entry) => addFormValue(form, key + "[]", entry))); + } else if (typeof value === "object") { + await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop))); + } else { + throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); + } +}; + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/resources/projects/repository/commits/commits.mjs +var BaseCommits3 = /* @__PURE__ */ (() => { + class BaseCommits4 extends APIResource3 { + /** + * This feature was introduced in GitLab 8.13 + * + * @example + * ```ts + * const apiEntitiesCommitDetail = + * await client.projects.repository.commits.create( + * 'string', + * { file: fs.createReadStream('path/to/file') }, + * ); + * ``` + */ + create(id, body, options) { + return this._client.post(path3`/projects/${id}/repository/commits`, multipartFormRequestOptions({ body, ...options }, this._client)); + } + /** + * Get a specific commit of a project + * + * @example + * ```ts + * const apiEntitiesCommitDetail = + * await client.projects.repository.commits.retrieve('sha', { + * id: 'string', + * }); + * ``` + */ + retrieve(sha, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/repository/commits/${sha}`, { query, ...options }); + } + /** + * Get a project repository commits + * + * @example + * ```ts + * const apiEntitiesCommits = + * await client.projects.repository.commits.list('string'); + * ``` + */ + list(id, query = {}, options) { + return this._client.get(path3`/projects/${id}/repository/commits`, { query, ...options }); + } + /** + * Authorize commits upload + * + * @example + * ```ts + * await client.projects.repository.commits.authorize( + * 'string', + * ); + * ``` + */ + authorize(id, options) { + return this._client.post(path3`/projects/${id}/repository/commits/authorize`, { + ...options, + headers: buildHeaders3([{ Accept: "*/*" }, options?.headers]) + }); + } + /** + * This feature was introduced in GitLab 8.15 + * + * @example + * ```ts + * const apiEntitiesCommit = + * await client.projects.repository.commits.cherryPick( + * 'sha', + * { id: 'string', branch: 'master' }, + * ); + * ``` + */ + cherryPick(sha, params, options) { + const { id, ...body } = params; + return this._client.post(path3`/projects/${id}/repository/commits/${sha}/cherry_pick`, { + body, + ...options + }); + } + /** + * Get the diff for a specific commit of a project + * + * @example + * ```ts + * const apiEntitiesDiffs = + * await client.projects.repository.commits.retrieveDiff( + * 'sha', + * { id: 'string' }, + * ); + * ``` + */ + retrieveDiff(sha, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/repository/commits/${sha}/diff`, { query, ...options }); + } + /** + * Get Merge Requests associated with a commit + * + * @example + * ```ts + * const apiEntitiesMergeRequestBasic = + * await client.projects.repository.commits.retrieveMergeRequests( + * 'sha', + * { id: 'string' }, + * ); + * ``` + */ + retrieveMergeRequests(sha, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/repository/commits/${sha}/merge_requests`, { + query, + ...options + }); } - case "python": { - if (head.install_url) { - installation = `pip install ${head.install_url}`; - } - break; + /** + * This feature was introduced in GitLab 10.6 + * + * @example + * ```ts + * const response = + * await client.projects.repository.commits.retrieveRefs( + * 'sha', + * { id: 'string' }, + * ); + * ``` + */ + retrieveRefs(sha, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/repository/commits/${sha}/refs`, { query, ...options }); } - case "go": { - if (githubGoURL) { - installation = `go get ${githubGoURL}`; - } - break; + /** + * Get the sequence count of a commit SHA + * + * @example + * ```ts + * const response = + * await client.projects.repository.commits.retrieveSequence( + * 'sha', + * { id: 'string' }, + * ); + * ``` + */ + retrieveSequence(sha, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/repository/commits/${sha}/sequence`, { query, ...options }); } - case "java": { - if (head.install_url) { - installation = `Add the following URL as a Maven source: '${head.install_url}'`; - } - break; + /** + * Get a commit's signature + * + * @example + * ```ts + * const response = + * await client.projects.repository.commits.retrieveSignature( + * 'sha', + * { id: 'string' }, + * ); + * ``` + */ + retrieveSignature(sha, params, options) { + const { id } = params; + return this._client.get(path3`/projects/${id}/repository/commits/${sha}/signature`, options); } - case "cli": { - if (head.install_url) { - installation = `Download and unzip: '${head.install_url}'. On macOS, run \`xattr -d com.apple.quarantine {executable name}\`.`; - } - break; + /** + * Get a commit's statuses + * + * @example + * ```ts + * const apiEntitiesCommitStatus = + * await client.projects.repository.commits.retrieveStatuses( + * '18f3e63d05582537db6d183d9d557be09e1f90c8', + * { id: 'string' }, + * ); + * ``` + */ + retrieveStatuses(sha, params, options) { + const { id, ...query } = params; + return this._client.get(path3`/projects/${id}/repository/commits/${sha}/statuses`, { query, ...options }); } - default: { - return null; + /** + * This feature was introduced in GitLab 11.5 + * + * @example + * ```ts + * const apiEntitiesCommit = + * await client.projects.repository.commits.revert('sha', { + * id: 'string', + * branch: 'master', + * }); + * ``` + */ + revert(sha, params, options) { + const { id, ...body } = params; + return this._client.post(path3`/projects/${id}/repository/commits/${sha}/revert`, { body, ...options }); } } - if (!installation) return null; - return CodeBlock({ content: installation, language: "bash" }); + BaseCommits4._key = Object.freeze([ + "projects", + "repository", + "commits" + ]); + return BaseCommits4; +})(); + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/tslib.mjs +function __classPrivateFieldSet3(receiver, state, value, kind, f) { + if (kind === "m") + throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; } -function parseCommitMessages(body) { - if (!body) { - return {}; +function __classPrivateFieldGet3(receiver, state, kind, f) { + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/utils/uuid.mjs +var uuid43 = function() { + const { crypto: crypto2 } = globalThis; + if (crypto2?.randomUUID) { + uuid43 = crypto2.randomUUID.bind(crypto2); + return crypto2.randomUUID(); } - const targetCommitMessages = {}; - const languageBlocks = body.matchAll( - /\*\*([a-z_]+)\*\*\s*\n```\s*\n([\s\S]*?)\n```/g - ); - for (const match of languageBlocks) { - const language = match[1]; - const message2 = match[2].trim(); - if (message2) { - targetCommitMessages[language] = makeCommitMessageConventional(message2); - } + const u8 = new Uint8Array(1); + const randomByte = crypto2 ? () => crypto2.getRandomValues(u8)[0] : () => Math.random() * 255 & 255; + return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16)); +}; + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/utils/sleep.mjs +var sleep3 = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/version.mjs +var VERSION3 = "0.3.0"; + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/detect-platform.mjs +function getDetectedPlatform3() { + if (typeof Deno !== "undefined" && Deno.build != null) { + return "deno"; } - if (Object.keys(targetCommitMessages).length > 0) { - return { targetCommitMessages }; + if (typeof EdgeRuntime !== "undefined") { + return "edge"; } - const message = body?.match(/(? comment.body?.includes(COMMENT_TITLE) - ); - if (!existingComment) { - return null; +var getPlatformProperties3 = () => { + const detectedPlatform = getDetectedPlatform3(); + if (detectedPlatform === "deno") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION3, + "X-Stainless-OS": normalizePlatform3(Deno.build.os), + "X-Stainless-Arch": normalizeArch3(Deno.build.arch), + "X-Stainless-Runtime": "deno", + "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown" + }; + } + if (typeof EdgeRuntime !== "undefined") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION3, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": `other:${EdgeRuntime}`, + "X-Stainless-Runtime": "edge", + "X-Stainless-Runtime-Version": globalThis.process.version + }; + } + if (detectedPlatform === "node") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION3, + "X-Stainless-OS": normalizePlatform3(globalThis.process.platform ?? "unknown"), + "X-Stainless-Arch": normalizeArch3(globalThis.process.arch ?? "unknown"), + "X-Stainless-Runtime": "node", + "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown" + }; + } + const browserInfo = getBrowserInfo3(); + if (browserInfo) { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION3, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": "unknown", + "X-Stainless-Runtime": `browser:${browserInfo.browser}`, + "X-Stainless-Runtime-Version": browserInfo.version + }; } return { - id: existingComment.id, - ...parseCommitMessages(existingComment.body) + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION3, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": "unknown", + "X-Stainless-Runtime": "unknown", + "X-Stainless-Runtime-Version": "unknown" }; -} -async function upsertComment(prNumber, { - body, - skipCreate = false -}) { - logger.debug(`Upserting comment on ${ctx().names.pr} #${prNumber}`); - const comments = await api().listComments(prNumber); - const firstLine = body.trim().split("\n")[0]; - const existingComment = comments.find( - (comment) => comment.body?.includes(firstLine) - ); - if (existingComment) { - logger.debug("Updating existing comment:", existingComment.id); - await api().updateComment(prNumber, { ...existingComment, body }); - } else if (!skipCreate) { - logger.debug("Creating new comment"); - await api().createComment(prNumber, { body }); +}; +function getBrowserInfo3() { + if (typeof navigator === "undefined" || !navigator) { + return null; } -} -function areCommentsEqual(a, b) { - return a.slice(0, a.indexOf(COMMENT_FOOTER_DIVIDER)) === b.slice(0, b.indexOf(COMMENT_FOOTER_DIVIDER)); -} -function commentThrottler(prNumber) { - let lastComment = null; - let lastCommentTime = null; - return async ({ body, force = false }) => { - if (force || !lastComment || !lastCommentTime || !areCommentsEqual(body, lastComment) && Date.now() - lastCommentTime.getTime() > 10 * 1e3 || Date.now() - lastCommentTime.getTime() > 30 * 1e3) { - await upsertComment(prNumber, { body }); - lastComment = body; - lastCommentTime = /* @__PURE__ */ new Date(); + const browserPatterns = [ + { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ } + ]; + for (const { key, pattern } of browserPatterns) { + const match = pattern.exec(navigator.userAgent); + if (match) { + const major = match[1] || 0; + const minor = match[2] || 0; + const patch = match[3] || 0; + return { browser: key, version: `${major}.${minor}.${patch}` }; } - }; + } + return null; } +var normalizeArch3 = (arch) => { + if (arch === "x32") + return "x32"; + if (arch === "x86_64" || arch === "x64") + return "x64"; + if (arch === "arm") + return "arm"; + if (arch === "aarch64" || arch === "arm64") + return "arm64"; + if (arch) + return `other:${arch}`; + return "unknown"; +}; +var normalizePlatform3 = (platform) => { + platform = platform.toLowerCase(); + if (platform.includes("ios")) + return "iOS"; + if (platform === "android") + return "Android"; + if (platform === "darwin") + return "MacOS"; + if (platform === "win32") + return "Windows"; + if (platform === "freebsd") + return "FreeBSD"; + if (platform === "openbsd") + return "OpenBSD"; + if (platform === "linux") + return "Linux"; + if (platform) + return `Other:${platform}`; + return "Unknown"; +}; +var _platformHeaders3; +var getPlatformHeaders3 = () => { + return _platformHeaders3 ?? (_platformHeaders3 = getPlatformProperties3()); +}; -// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/context.js -var import_node_process = __toESM(require("node:process"), 1); -var import_node_util = require("node:util"); -var getContext = (raw) => ({ - start: import_node_process.default.hrtime.bigint(), - command: raw.map((part) => getCommandPart((0, import_node_util.stripVTControlCharacters)(part))).join(" "), - state: { stdout: "", stderr: "", output: "" } -}); -var getCommandPart = (part) => /[^\w./-]/.test(part) ? `'${part.replaceAll("'", "'\\''")}'` : part; - -// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/options.js -var import_node_path = __toESM(require("node:path"), 1); -var import_node_url = require("node:url"); -var import_node_process2 = __toESM(require("node:process"), 1); -var getOptions = ({ - stdin, - stdout, - stderr, - stdio = [stdin, stdout, stderr], - env: envOption, - preferLocal, - cwd: cwdOption = ".", - ...options -}) => { - const cwd = cwdOption instanceof URL ? (0, import_node_url.fileURLToPath)(cwdOption) : import_node_path.default.resolve(cwdOption); - const env = envOption ? { ...import_node_process2.default.env, ...envOption } : void 0; - const input = stdio[0]?.string; +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/request-options.mjs +var FallbackEncoder3 = ({ headers, body }) => { return { - ...options, - input, - stdio: input === void 0 ? stdio : ["pipe", ...stdio.slice(1)], - env: preferLocal ? addLocalPath(env ?? import_node_process2.default.env, cwd) : env, - cwd + bodyHeaders: { + "content-type": "application/json" + }, + body: JSON.stringify(body) }; }; -var addLocalPath = ({ Path: Path3 = "", PATH = Path3, ...env }, cwd) => { - const pathParts = PATH.split(import_node_path.default.delimiter); - const localPaths = getLocalPaths([], import_node_path.default.resolve(cwd)).map((localPath) => import_node_path.default.join(localPath, "node_modules/.bin")).filter((localPath) => !pathParts.includes(localPath)); - return { ...env, PATH: [...localPaths, PATH].filter(Boolean).join(import_node_path.default.delimiter) }; -}; -var getLocalPaths = (localPaths, localPath) => localPaths.at(-1) === localPath ? localPaths : getLocalPaths([...localPaths, localPath], import_node_path.default.resolve(localPath, "..")); -// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/spawn.js -var import_node_child_process = require("node:child_process"); -var import_node_events2 = require("node:events"); -var import_node_process5 = __toESM(require("node:process"), 1); - -// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/windows.js -var import_promises = __toESM(require("node:fs/promises"), 1); -var import_node_path2 = __toESM(require("node:path"), 1); -var import_node_process3 = __toESM(require("node:process"), 1); -var applyForceShell = async (file, commandArguments, options) => await shouldForceShell(file, options) ? [escapeFile(file), commandArguments.map((argument) => escapeArgument(argument)), { ...options, shell: true }] : [file, commandArguments, options]; -var shouldForceShell = async (file, { shell, cwd, env = import_node_process3.default.env }) => import_node_process3.default.platform === "win32" && !shell && !await isExe(file, cwd, env); -var isExe = (file, cwd, { Path: Path3 = "", PATH = Path3 }) => ( - // If the *.exe or *.com file extension was not omitted. - // Windows common file systems are case-insensitive. - exeExtensions.some((extension) => file.toLowerCase().endsWith(extension)) || mIsExe(file, cwd, PATH) -); -var EXE_MEMO = {}; -var memoize = (function_) => (...arguments_) => ( - // Use returned assignment to keep code small - EXE_MEMO[arguments_.join("\0")] ??= function_(...arguments_) -); -var access = memoize(import_promises.default.access); -var mIsExe = memoize(async (file, cwd, PATH) => { - const parts = PATH.split(import_node_path2.default.delimiter).filter(Boolean).map((part) => part.replace(/^"(.*)"$/, "$1")); - try { - await Promise.any( - [cwd, ...parts].flatMap( - (part) => exeExtensions.map((extension) => access(`${import_node_path2.default.resolve(part, file)}${extension}`)) - ) - ); - } catch { - return false; - } - return true; -}); -var exeExtensions = [".exe", ".com"]; -var escapeArgument = (argument) => escapeFile(escapeFile(`"${argument.replaceAll(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, "$1$1")}"`)); -var escapeFile = (file) => file.replaceAll(/([()\][%!^"`<>&|;, *?])/g, "^$1"); +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/qs/formats.mjs +var default_format3 = "RFC3986"; +var default_formatter3 = (v) => String(v); +var formatters3 = { + RFC1738: (v) => String(v).replace(/%20/g, "+"), + RFC3986: default_formatter3 +}; +var RFC17383 = "RFC1738"; -// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/result.js -var import_node_events = require("node:events"); -var import_node_process4 = __toESM(require("node:process"), 1); -var getResult = async (nodeChildProcess, { input }, context) => { - const instance = await nodeChildProcess; - if (input !== void 0) { - instance.stdin.end(input); - } - const onClose = (0, import_node_events.once)(instance, "close"); - try { - await Promise.race([ - onClose, - ...instance.stdio.filter(Boolean).map((stream) => onStreamError(stream)) - ]); - checkFailure(context, getErrorOutput(instance)); - return getOutputs(context); - } catch (error) { - await Promise.allSettled([onClose]); - throw getResultError(error, instance, context); +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/qs/utils.mjs +var has3 = (obj, key) => (has3 = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has3(obj, key)); +var hex_table3 = /* @__PURE__ */ (() => { + const array = []; + for (let i = 0; i < 256; ++i) { + array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase()); } -}; -var onStreamError = async (stream) => { - for await (const [error] of (0, import_node_events.on)(stream, "error")) { - if (!["ERR_STREAM_PREMATURE_CLOSE", "EPIPE"].includes(error?.code)) { - throw error; - } + return array; +})(); +var limit3 = 1024; +var encode3 = (str, _defaultEncoder, charset, _kind, format) => { + if (str.length === 0) { + return str; } -}; -var checkFailure = ({ command }, { exitCode, signalName }) => { - if (signalName !== void 0) { - throw new SubprocessError(`Command was terminated with ${signalName}: ${command}`); + let string = str; + if (typeof str === "symbol") { + string = Symbol.prototype.toString.call(str); + } else if (typeof str !== "string") { + string = String(str); } - if (exitCode !== void 0) { - throw new SubprocessError(`Command failed with exit code ${exitCode}: ${command}`); + if (charset === "iso-8859-1") { + return escape(string).replace(/%u[0-9a-f]{4}/gi, function($0) { + return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; + }); } -}; -var getResultError = (error, instance, context) => Object.assign( - getErrorInstance(error, context), - getErrorOutput(instance), - getOutputs(context) -); -var getErrorInstance = (error, { command }) => error instanceof SubprocessError ? error : new SubprocessError(`Command failed: ${command}`, { cause: error }); -var SubprocessError = class extends Error { - name = "SubprocessError"; -}; -var getErrorOutput = ({ exitCode, signalCode }) => ({ - // `exitCode` can be a negative number (`errno`) when the `error` event is emitted on the `instance` - ...exitCode < 1 ? {} : { exitCode }, - ...signalCode === null ? {} : { signalName: signalCode } -}); -var getOutputs = ({ state: { stdout, stderr, output }, command, start }) => ({ - stdout: getOutput(stdout), - stderr: getOutput(stderr), - output: getOutput(output), - command, - durationMs: Number(import_node_process4.default.hrtime.bigint() - start) / 1e6 -}); -var getOutput = (output) => output.at(-1) === "\n" ? output.slice(0, output.at(-2) === "\r" ? -2 : -1) : output; - -// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/spawn.js -var spawnSubprocess = async (file, commandArguments, options, context) => { - try { - if (["node", "node.exe"].includes(file.toLowerCase())) { - file = import_node_process5.default.execPath; - commandArguments = [...import_node_process5.default.execArgv.filter((flag) => !flag.startsWith("--inspect")), ...commandArguments]; + let out = ""; + for (let j = 0; j < string.length; j += limit3) { + const segment = string.length >= limit3 ? string.slice(j, j + limit3) : string; + const arr = []; + for (let i = 0; i < segment.length; ++i) { + let c = segment.charCodeAt(i); + if (c === 45 || // - + c === 46 || // . + c === 95 || // _ + c === 126 || // ~ + c >= 48 && c <= 57 || // 0-9 + c >= 65 && c <= 90 || // a-z + c >= 97 && c <= 122 || // A-Z + format === RFC17383 && (c === 40 || c === 41)) { + arr[arr.length] = segment.charAt(i); + continue; + } + if (c < 128) { + arr[arr.length] = hex_table3[c]; + continue; + } + if (c < 2048) { + arr[arr.length] = hex_table3[192 | c >> 6] + hex_table3[128 | c & 63]; + continue; + } + if (c < 55296 || c >= 57344) { + arr[arr.length] = hex_table3[224 | c >> 12] + hex_table3[128 | c >> 6 & 63] + hex_table3[128 | c & 63]; + continue; + } + i += 1; + c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023); + arr[arr.length] = hex_table3[240 | c >> 18] + hex_table3[128 | c >> 12 & 63] + hex_table3[128 | c >> 6 & 63] + hex_table3[128 | c & 63]; } - [file, commandArguments, options] = await applyForceShell(file, commandArguments, options); - [file, commandArguments, options] = concatenateShell(file, commandArguments, options); - const instance = (0, import_node_child_process.spawn)(file, commandArguments, options); - bufferOutput(instance.stdout, context, "stdout"); - bufferOutput(instance.stderr, context, "stderr"); - instance.once("error", () => { - }); - await (0, import_node_events2.once)(instance, "spawn"); - return instance; - } catch (error) { - throw getResultError(error, {}, context); + out += arr.join(""); } + return out; }; -var concatenateShell = (file, commandArguments, options) => options.shell && commandArguments.length > 0 ? [[file, ...commandArguments].join(" "), [], options] : [file, commandArguments, options]; -var bufferOutput = (stream, { state }, streamName) => { - if (stream) { - stream.setEncoding("utf8"); - if (!state.isIterating) { - state.isIterating = false; - stream.on("data", (chunk) => { - state[streamName] += chunk; - state.output += chunk; - }); +function is_buffer3(obj) { + if (!obj || typeof obj !== "object") { + return false; + } + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +} +function maybe_map3(val, fn) { + if (isArray3(val)) { + const mapped = []; + for (let i = 0; i < val.length; i += 1) { + mapped.push(fn(val[i])); } + return mapped; } -}; + return fn(val); +} -// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/pipe.js -var import_promises2 = require("node:stream/promises"); -var handlePipe = async (subprocesses) => { - const [[from, to]] = await Promise.all([Promise.allSettled(subprocesses), pipeStreams(subprocesses)]); - if (to.reason) { - to.reason.pipedFrom = from.reason ?? from.value; - throw to.reason; - } - if (from.reason) { - throw from.reason; +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/qs/stringify.mjs +var array_prefix_generators3 = { + brackets(prefix) { + return String(prefix) + "[]"; + }, + comma: "comma", + indices(prefix, key) { + return String(prefix) + "[" + key + "]"; + }, + repeat(prefix) { + return String(prefix); } - return { ...to.value, pipedFrom: from.value }; }; -var pipeStreams = async (subprocesses) => { - try { - const [{ stdout }, { stdin }] = await Promise.all(subprocesses.map(({ nodeChildProcess }) => nodeChildProcess)); - if (stdin === null) { - throw new Error('The "stdin" option must be set on the first "spawn()" call in the pipeline.'); - } - if (stdout === null) { - throw new Error('The "stdout" option must be set on the last "spawn()" call in the pipeline.'); - } - (0, import_promises2.pipeline)(stdout, stdin).catch(() => { - }); - } catch (error) { - await Promise.allSettled(subprocesses.map(({ nodeChildProcess }) => closeStdin(nodeChildProcess))); - throw error; - } +var push_to_array3 = function(arr, value_or_array) { + Array.prototype.push.apply(arr, isArray3(value_or_array) ? value_or_array : [value_or_array]); }; -var closeStdin = async (nodeChildProcess) => { - const { stdin } = await nodeChildProcess; - stdin.end(); +var toISOString3; +var defaults3 = { + addQueryPrefix: false, + allowDots: false, + allowEmptyArrays: false, + arrayFormat: "indices", + charset: "utf-8", + charsetSentinel: false, + delimiter: "&", + encode: true, + encodeDotInKeys: false, + encoder: encode3, + encodeValuesOnly: false, + format: default_format3, + formatter: default_formatter3, + /** @deprecated */ + indices: false, + serializeDate(date) { + return (toISOString3 ?? (toISOString3 = Function.prototype.call.bind(Date.prototype.toISOString)))(date); + }, + skipNulls: false, + strictNullHandling: false }; - -// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/iterable.js -var readline = __toESM(require("node:readline/promises"), 1); -var lineIterator = async function* (subprocess, { state }, streamName) { - if (state.isIterating === false) { - throw new Error(`The subprocess must be iterated right away, for example: - for await (const line of spawn(...)) { ... }`); - } - state.isIterating = true; - try { - const { [streamName]: stream } = await subprocess.nodeChildProcess; - if (!stream) { - return; +function is_non_nullish_primitive3(v) { + return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint"; +} +var sentinel3 = {}; +function inner_stringify3(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { + let obj = object; + let tmp_sc = sideChannel; + let step = 0; + let find_flag = false; + while ((tmp_sc = tmp_sc.get(sentinel3)) !== void 0 && !find_flag) { + const pos = tmp_sc.get(object); + step += 1; + if (typeof pos !== "undefined") { + if (pos === step) { + throw new RangeError("Cyclic object value"); + } else { + find_flag = true; + } + } + if (typeof tmp_sc.get(sentinel3) === "undefined") { + step = 0; } - handleErrors(subprocess); - yield* readline.createInterface({ input: stream }); - } finally { - await subprocess; - } -}; -var handleErrors = async (subprocess) => { - try { - await subprocess; - } catch { } -}; -var combineAsyncIterators = async function* (...iterators) { - try { - let promises = []; - while (iterators.length > 0) { - promises = iterators.map((iterator2, index2) => promises[index2] ?? getNext(iterator2)); - const [{ value, done }, index] = await Promise.race(promises.map((promise, index2) => Promise.all([promise, index2]))); - const [iterator] = iterators.splice(index, 1); - promises.splice(index, 1); - if (!done) { - iterators.push(iterator); - yield value; + if (typeof filter === "function") { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate?.(obj); + } else if (generateArrayPrefix === "comma" && isArray3(obj)) { + obj = maybe_map3(obj, function(value) { + if (value instanceof Date) { + return serializeDate?.(value); } + return value; + }); + } + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? ( + // @ts-expect-error + encoder(prefix, defaults3.encoder, charset, "key", format) + ) : prefix; } - } finally { - await Promise.all(iterators.map((iterator) => iterator.return())); + obj = ""; } -}; -var getNext = async (iterator) => { - try { - return await iterator.next(); - } catch (error) { - await iterator.throw(error); + if (is_non_nullish_primitive3(obj) || is_buffer3(obj)) { + if (encoder) { + const key_value = encodeValuesOnly ? prefix : encoder(prefix, defaults3.encoder, charset, "key", format); + return [ + formatter?.(key_value) + "=" + // @ts-expect-error + formatter?.(encoder(obj, defaults3.encoder, charset, "value", format)) + ]; + } + return [formatter?.(prefix) + "=" + formatter?.(String(obj))]; } -}; - -// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/index.js -function spawn2(file, second, third, previous) { - const [commandArguments = [], options = {}] = Array.isArray(second) ? [second, third] : [[], second]; - const context = getContext([file, ...commandArguments]); - const spawnOptions = getOptions(options); - const nodeChildProcess = spawnSubprocess(file, commandArguments, spawnOptions, context); - let subprocess = getResult(nodeChildProcess, spawnOptions, context); - Object.assign(subprocess, { nodeChildProcess }); - subprocess = previous ? handlePipe([previous, subprocess]) : subprocess; - const stdout = lineIterator(subprocess, context, "stdout"); - const stderr = lineIterator(subprocess, context, "stderr"); - return Object.assign(subprocess, { - nodeChildProcess, - stdout, - stderr, - [Symbol.asyncIterator]: () => combineAsyncIterators(stdout, stderr), - pipe: (file2, second2, third2) => spawn2(file2, second2, third2, subprocess) - }); -} - -// src/config.ts -var fs4 = __toESM(require("node:fs")); -var import_node_os = require("node:os"); -var path5 = __toESM(require("node:path")); -function getSavedFilePath(file, sha, extension) { - return path5.join( - (0, import_node_os.tmpdir)(), - "stainless-generated-config", - `${file}-${sha}${extension}` - ); -} -async function saveConfig({ - oasPath, - configPath -}) { - let hasOAS = false; - let hasConfig = false; - const savedSha = (await spawn2("git", ["rev-parse", "HEAD"])).stdout.trim(); - if (!savedSha) { - throw new Error("Unable to determine current SHA; is there a git repo?"); + const values = []; + if (typeof obj === "undefined") { + return values; } - logger.info("Saving generated config for", savedSha); - if (oasPath && fs4.existsSync(oasPath)) { - hasOAS = true; - const savedFilePath = getSavedFilePath( - "oas", - savedSha, - path5.extname(oasPath) - ); - fs4.mkdirSync(path5.dirname(savedFilePath), { recursive: true }); - fs4.copyFileSync(oasPath, savedFilePath); - fs4.rmSync(oasPath); - logger.info(`Saved OAS file to ${savedFilePath}`); + let obj_keys; + if (generateArrayPrefix === "comma" && isArray3(obj)) { + if (encodeValuesOnly && encoder) { + obj = maybe_map3(obj, encoder); + } + obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; + } else if (isArray3(filter)) { + obj_keys = filter; + } else { + const keys = Object.keys(obj); + obj_keys = sort ? keys.sort(sort) : keys; } - if (configPath && fs4.existsSync(configPath)) { - hasConfig = true; - const savedFilePath = getSavedFilePath( - "config", - savedSha, - path5.extname(configPath) + const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix); + const adjusted_prefix = commaRoundTrip && isArray3(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix; + if (allowEmptyArrays && isArray3(obj) && obj.length === 0) { + return adjusted_prefix + "[]"; + } + for (let j = 0; j < obj_keys.length; ++j) { + const key = obj_keys[j]; + const value = ( + // @ts-ignore + typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key] ); - fs4.mkdirSync(path5.dirname(savedFilePath), { recursive: true }); - fs4.copyFileSync(configPath, savedFilePath); - fs4.rmSync(configPath); - logger.info(`Saved config file to ${savedFilePath}`); + if (skipNulls && value === null) { + continue; + } + const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key; + const key_prefix = isArray3(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]"); + sideChannel.set(object, step); + const valueSideChannel = /* @__PURE__ */ new WeakMap(); + valueSideChannel.set(sentinel3, sideChannel); + push_to_array3(values, inner_stringify3( + value, + key_prefix, + generateArrayPrefix, + commaRoundTrip, + allowEmptyArrays, + strictNullHandling, + skipNulls, + encodeDotInKeys, + // @ts-ignore + generateArrayPrefix === "comma" && encodeValuesOnly && isArray3(obj) ? null : encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + valueSideChannel + )); } - return { hasOAS, hasConfig, savedSha }; + return values; } -async function readConfig({ - oasPath, - configPath, - sha, - required = false -}) { - sha ??= (await spawn2("git", ["rev-parse", "HEAD"])).stdout; - if (!sha) { - throw new Error("Unable to determine current SHA; is there a git repo?"); +function normalize_stringify_options3(opts = defaults3) { + if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") { + throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); } - logger.info("Reading config at SHA", sha); - const results = {}; - const addToResults = async (file, filePath, via) => { - if (results[file]) { - return; - } - if (!filePath || !fs4.existsSync(filePath)) { - logger.debug(`Skipping missing ${file} at ${filePath}`); - return; - } - results[file] = fs4.readFileSync(filePath, "utf-8"); - results[`${file}Hash`] = (await spawn2("md5sum", [filePath])).stdout.split( - " " - )[0]; - logger.info(`Using ${file} via ${via}`, { hash: results[`${file}Hash`] }); - }; - try { - await spawn2("git", ["fetch", "--depth=1", "origin", sha]).catch(() => null); - await spawn2("git", ["checkout", sha, "--", "."]); - } catch { - logger.debug("Could not checkout", sha); + if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") { + throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided"); } - await addToResults("oas", oasPath, `git ${sha}`); - await addToResults("config", configPath, `git ${sha}`); - try { - await addToResults( - "oas", - getSavedFilePath("oas", sha, path5.extname(oasPath ?? "")), - `saved ${sha}` - ); - await addToResults( - "config", - getSavedFilePath("config", sha, path5.extname(configPath ?? "")), - `saved ${sha}` - ); - } catch (e) { - logger.info(`Could not get config from saved file path: ${e}`); - logger.debug("Could not get config from saved file path"); + if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") { + throw new TypeError("Encoder has to be a function."); } - if (required) { - if (oasPath && !results.oas) { - throw new Error(`Missing OpenAPI spec at ${oasPath} for ${sha}`); - } - if (configPath && !results.config) { - throw new Error(`Missing config at ${configPath} for ${sha}`); + const charset = opts.charset || defaults3.charset; + if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { + throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); + } + let format = default_format3; + if (typeof opts.format !== "undefined") { + if (!has3(formatters3, opts.format)) { + throw new TypeError("Unknown format option provided."); } + format = opts.format; } - return results; + const formatter = formatters3[format]; + let filter = defaults3.filter; + if (typeof opts.filter === "function" || isArray3(opts.filter)) { + filter = opts.filter; + } + let arrayFormat; + if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators3) { + arrayFormat = opts.arrayFormat; + } else if ("indices" in opts) { + arrayFormat = opts.indices ? "indices" : "repeat"; + } else { + arrayFormat = defaults3.arrayFormat; + } + if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") { + throw new TypeError("`commaRoundTrip` must be a boolean, or absent"); + } + const allowDots = typeof opts.allowDots === "undefined" ? !!opts.encodeDotInKeys === true ? true : defaults3.allowDots : !!opts.allowDots; + return { + addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults3.addQueryPrefix, + // @ts-ignore + allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults3.allowEmptyArrays, + arrayFormat, + charset, + charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults3.charsetSentinel, + commaRoundTrip: !!opts.commaRoundTrip, + delimiter: typeof opts.delimiter === "undefined" ? defaults3.delimiter : opts.delimiter, + encode: typeof opts.encode === "boolean" ? opts.encode : defaults3.encode, + encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults3.encodeDotInKeys, + encoder: typeof opts.encoder === "function" ? opts.encoder : defaults3.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults3.encodeValuesOnly, + filter, + format, + formatter, + serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults3.serializeDate, + skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults3.skipNulls, + // @ts-ignore + sort: typeof opts.sort === "function" ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults3.strictNullHandling + }; } -async function getMergeBase({ - baseSha, - headSha -}) { - try { - await spawn2("git", ["fetch", "--depth=1", "origin", baseSha, headSha]); - } catch { - throw new Error( - `Cannot fetch ${baseSha} or ${headSha} from origin. Is there a git repo?` - ); +function stringify3(object, opts = {}) { + let obj = object; + const options = normalize_stringify_options3(opts); + let obj_keys; + let filter; + if (typeof options.filter === "function") { + filter = options.filter; + obj = filter("", obj); + } else if (isArray3(options.filter)) { + filter = options.filter; + obj_keys = filter; } - let mergeBaseSha; - try { - const output = await spawn2("git", ["merge-base", headSha, baseSha]); - mergeBaseSha = output.stdout.trim(); - } catch { + const keys = []; + if (typeof obj !== "object" || obj === null) { + return ""; } - const deepenAmounts = [50, 100, 200, 400]; - for (const deepenAmount of deepenAmounts) { - if (mergeBaseSha) break; - try { - await spawn2("git", [ - "fetch", - "--quiet", - `--deepen=${deepenAmount}`, - "origin" - ]); - } catch { - } - try { - const output = await spawn2("git", ["merge-base", headSha, baseSha]); - mergeBaseSha = output.stdout.trim(); - if (mergeBaseSha) break; - } catch { - } + const generateArrayPrefix = array_prefix_generators3[options.arrayFormat]; + const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip; + if (!obj_keys) { + obj_keys = Object.keys(obj); } - if (!mergeBaseSha) { - console.log("Deepening did not find merge base, trying unshallow fetch..."); - try { - await spawn2("git", ["fetch", "--quiet", "--unshallow", "origin"]); - } catch { + if (options.sort) { + obj_keys.sort(options.sort); + } + const sideChannel = /* @__PURE__ */ new WeakMap(); + for (let i = 0; i < obj_keys.length; ++i) { + const key = obj_keys[i]; + if (options.skipNulls && obj[key] === null) { + continue; } - try { - const output = await spawn2("git", ["merge-base", headSha, baseSha]); - mergeBaseSha = output.stdout.trim(); - } catch { + push_to_array3(keys, inner_stringify3( + obj[key], + key, + // @ts-expect-error + generateArrayPrefix, + commaRoundTrip, + options.allowEmptyArrays, + options.strictNullHandling, + options.skipNulls, + options.encodeDotInKeys, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.format, + options.formatter, + options.encodeValuesOnly, + options.charset, + sideChannel + )); + } + const joined = keys.join(options.delimiter); + let prefix = options.addQueryPrefix === true ? "?" : ""; + if (options.charsetSentinel) { + if (options.charset === "iso-8859-1") { + prefix += "utf8=%26%2310003%3B&"; + } else { + prefix += "utf8=%E2%9C%93&"; } } - if (!mergeBaseSha) { - throw new Error( - `Could not determine merge base SHA between ${headSha} and ${baseSha}. This may happen if the branches have completely diverged or if there is insufficient git history. Try using 'fetch-depth: 0' in your checkout step.` - ); + return joined.length > 0 ? prefix + joined : ""; +} + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/utils/log.mjs +var levelNumbers3 = { + off: 0, + error: 200, + warn: 300, + info: 400, + debug: 500 +}; +var parseLogLevel3 = (maybeLevel, sourceName, client) => { + if (!maybeLevel) { + return void 0; + } + if (hasOwn3(levelNumbers3, maybeLevel)) { + return maybeLevel; } - logger.debug(`Merge base: ${mergeBaseSha}`); - return { mergeBaseSha }; + loggerFor3(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers3))}`); + return void 0; +}; +function noop3() { } -async function getNonMainBaseRef({ - baseRef, - defaultBranch -}) { - let nonMainBaseRef; - if (baseRef !== defaultBranch) { - nonMainBaseRef = `preview/${baseRef}`; - logger.debug(`Non-main base ref: ${nonMainBaseRef}`); +function makeLogFn3(fnLevel, logger2, logLevel) { + if (!logger2 || levelNumbers3[fnLevel] > levelNumbers3[logLevel]) { + return noop3; + } else { + return logger2[fnLevel].bind(logger2); } - return { nonMainBaseRef }; } -async function isConfigChanged({ - before, - after -}) { - let changed = false; - if (before.oasHash !== after.oasHash) { - logger.debug("OAS file changed"); - changed = true; +var noopLogger3 = { + error: noop3, + warn: noop3, + info: noop3, + debug: noop3 +}; +var cachedLoggers3 = /* @__PURE__ */ new WeakMap(); +function loggerFor3(client) { + const logger2 = client.logger; + const logLevel = client.logLevel ?? "off"; + if (!logger2) { + return noopLogger3; } - if (before.configHash !== after.configHash) { - logger.debug("Config file changed"); - changed = true; + const cachedLogger = cachedLoggers3.get(logger2); + if (cachedLogger && cachedLogger[0] === logLevel) { + return cachedLogger[1]; } - return changed; + const levelLogger = { + error: makeLogFn3("error", logger2, logLevel), + warn: makeLogFn3("warn", logger2, logLevel), + info: makeLogFn3("info", logger2, logLevel), + debug: makeLogFn3("debug", logger2, logLevel) + }; + cachedLoggers3.set(logger2, [logLevel, levelLogger]); + return levelLogger; } - -// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/diff/base.js -var Diff = class { - diff(oldStr, newStr, options = {}) { - let callback; - if (typeof options === "function") { - callback = options; - options = {}; - } else if ("callback" in options) { - callback = options.callback; +var formatRequestDetails3 = (details) => { + if (details.options) { + details.options = { ...details.options }; + delete details.options["headers"]; + } + if (details.headers) { + details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ + name, + name.toLowerCase() === "authorization" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value + ])); + } + if ("retryOfRequestLogID" in details) { + if (details.retryOfRequestLogID) { + details.retryOf = details.retryOfRequestLogID; } - const oldString = this.castInput(oldStr, options); - const newString = this.castInput(newStr, options); - const oldTokens = this.removeEmpty(this.tokenize(oldString, options)); - const newTokens = this.removeEmpty(this.tokenize(newString, options)); - return this.diffWithOptionsObj(oldTokens, newTokens, options, callback); + delete details.retryOfRequestLogID; } - diffWithOptionsObj(oldTokens, newTokens, options, callback) { - var _a2; - const done = (value) => { - value = this.postProcess(value, options); - if (callback) { - setTimeout(function() { - callback(value); - }, 0); + return details; +}; + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/parse.mjs +async function defaultParseResponse3(client, props) { + const { response, requestLogID, retryOfRequestLogID, startTime } = props; + const body = await (async () => { + if (response.status === 204) { + return null; + } + if (props.options.__binaryResponse) { + return response; + } + const contentType = response.headers.get("content-type"); + const mediaType = contentType?.split(";")[0]?.trim(); + const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json"); + if (isJSON) { + const contentLength = response.headers.get("content-length"); + if (contentLength === "0") { return void 0; - } else { - return value; } - }; - const newLen = newTokens.length, oldLen = oldTokens.length; - let editLength = 1; - let maxEditLength = newLen + oldLen; - if (options.maxEditLength != null) { - maxEditLength = Math.min(maxEditLength, options.maxEditLength); + const json = await response.json(); + return json; } - const maxExecutionTime = (_a2 = options.timeout) !== null && _a2 !== void 0 ? _a2 : Infinity; - const abortAfterTimestamp = Date.now() + maxExecutionTime; - const bestPath = [{ oldPos: -1, lastComponent: void 0 }]; - let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options); - if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) { - return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens)); + const text = await response.text(); + return text; + })(); + loggerFor3(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails3({ + retryOfRequestLogID, + url: response.url, + status: response.status, + body, + durationMs: Date.now() - startTime + })); + return body; +} + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/core/api-promise.mjs +var _APIPromise_client3; +var APIPromise3 = /* @__PURE__ */ (() => { + class APIPromise4 extends Promise { + constructor(client, responsePromise, parseResponse = defaultParseResponse3) { + super((resolve) => { + resolve(null); + }); + this.responsePromise = responsePromise; + this.parseResponse = parseResponse; + _APIPromise_client3.set(this, void 0); + __classPrivateFieldSet3(this, _APIPromise_client3, client, "f"); } - let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity; - const execEditLength = () => { - for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) { - let basePath; - const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1]; - if (removePath) { - bestPath[diagonalPath - 1] = void 0; - } - let canAdd = false; - if (addPath) { - const addPathNewPos = addPath.oldPos - diagonalPath; - canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen; - } - const canRemove = removePath && removePath.oldPos + 1 < oldLen; - if (!canAdd && !canRemove) { - bestPath[diagonalPath] = void 0; - continue; - } - if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) { - basePath = this.addToPath(addPath, true, false, 0, options); - } else { - basePath = this.addToPath(removePath, false, true, 1, options); - } - newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options); - if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) { - return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true; - } else { - bestPath[diagonalPath] = basePath; - if (basePath.oldPos + 1 >= oldLen) { - maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1); - } - if (newPos + 1 >= newLen) { - minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1); - } - } - } - editLength++; - }; - if (callback) { - (function exec() { - setTimeout(function() { - if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) { - return callback(void 0); - } - if (!execEditLength()) { - exec(); - } - }, 0); - })(); - } else { - while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) { - const ret = execEditLength(); - if (ret) { - return ret; - } - } + _thenUnwrap(transform) { + return new APIPromise4(__classPrivateFieldGet3(this, _APIPromise_client3, "f"), this.responsePromise, async (client, props) => transform(await this.parseResponse(client, props), props)); } - } - addToPath(path7, added, removed, oldPosInc, options) { - const last = path7.lastComponent; - if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) { - return { - oldPos: path7.oldPos + oldPosInc, - lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent } - }; - } else { - return { - oldPos: path7.oldPos + oldPosInc, - lastComponent: { count: 1, added, removed, previousComponent: last } - }; + /** + * Gets the raw `Response` instance instead of parsing the response + * data. + * + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + asResponse() { + return this.responsePromise.then((p) => p.response); + } + /** + * Gets the parsed response data and the raw `Response` instance. + * + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + async withResponse() { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { data, response }; } - } - extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) { - const newLen = newTokens.length, oldLen = oldTokens.length; - let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0; - while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) { - newPos++; - oldPos++; - commonCount++; - if (options.oneChangePerToken) { - basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false }; + parse() { + if (!this.parsedPromise) { + this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet3(this, _APIPromise_client3, "f"), data)); } + return this.parsedPromise; } - if (commonCount && !options.oneChangePerToken) { - basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false }; + then(onfulfilled, onrejected) { + return this.parse().then(onfulfilled, onrejected); } - basePath.oldPos = oldPos; - return newPos; - } - equals(left, right, options) { - if (options.comparator) { - return options.comparator(left, right); - } else { - return left === right || !!options.ignoreCase && left.toLowerCase() === right.toLowerCase(); + catch(onrejected) { + return this.parse().catch(onrejected); } - } - removeEmpty(array) { - const ret = []; - for (let i = 0; i < array.length; i++) { - if (array[i]) { - ret.push(array[i]); - } + finally(onfinally) { + return this.parse().finally(onfinally); } - return ret; - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - castInput(value, options) { - return value; - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - tokenize(value, options) { - return Array.from(value); - } - join(chars) { - return chars.join(""); - } - postProcess(changeObjects, options) { - return changeObjects; } - get useLongestToken() { - return false; + _APIPromise_client3 = /* @__PURE__ */ new WeakMap(); + return APIPromise4; +})(); + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/internal/utils/env.mjs +var readEnv3 = (env) => { + if (typeof globalThis.process !== "undefined") { + return globalThis.process.env?.[env]?.trim() ?? void 0; } - buildValues(lastComponent, newTokens, oldTokens) { - const components = []; - let nextComponent; - while (lastComponent) { - components.push(lastComponent); - nextComponent = lastComponent.previousComponent; - delete lastComponent.previousComponent; - lastComponent = nextComponent; - } - components.reverse(); - const componentLen = components.length; - let componentPos = 0, newPos = 0, oldPos = 0; - for (; componentPos < componentLen; componentPos++) { - const component = components[componentPos]; - if (!component.removed) { - if (!component.added && this.useLongestToken) { - let value = newTokens.slice(newPos, newPos + component.count); - value = value.map(function(value2, i) { - const oldValue = oldTokens[oldPos + i]; - return oldValue.length > value2.length ? oldValue : value2; - }); - component.value = this.join(value); - } else { - component.value = this.join(newTokens.slice(newPos, newPos + component.count)); - } - newPos += component.count; - if (!component.added) { - oldPos += component.count; - } - } else { - component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count)); - oldPos += component.count; - } - } - return components; + if (typeof globalThis.Deno !== "undefined") { + return globalThis.Deno.env?.get?.(env)?.trim(); } + return void 0; }; -// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/util/string.js -function hasOnlyWinLineEndings(string) { - return string.includes("\r\n") && !string.startsWith("\n") && !string.match(/[^\r]\n/); -} -function hasOnlyUnixLineEndings(string) { - return !string.includes("\r\n") && string.includes("\n"); -} - -// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/diff/line.js -var LineDiff = class extends Diff { - constructor() { - super(...arguments); - this.tokenize = tokenize; - } - equals(left, right, options) { - if (options.ignoreWhitespace) { - if (!options.newlineIsToken || !left.includes("\n")) { - left = left.trim(); - } - if (!options.newlineIsToken || !right.includes("\n")) { - right = right.trim(); - } - } else if (options.ignoreNewlineAtEof && !options.newlineIsToken) { - if (left.endsWith("\n")) { - left = left.slice(0, -1); - } - if (right.endsWith("\n")) { - right = right.slice(0, -1); +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/client.mjs +var _BaseGitLab_instances; +var _BaseGitLab_encoder; +var _BaseGitLab_baseURLOverridden; +var BaseGitLab = /* @__PURE__ */ (() => { + class BaseGitLab2 { + /** + * API Client for interfacing with the GitLab API. + * + * @param {string | undefined} [opts.apiToken=process.env['GITLAB_API_TOKEN'] ?? undefined] + * @param {string} [opts.baseURL=process.env['GITLAB_BASE_URL'] ?? https://gitlab.com/api/v4] - Override the default base URL for the API. + * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. + * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. + */ + constructor({ baseURL = readEnv3("GITLAB_BASE_URL"), apiToken = readEnv3("GITLAB_API_TOKEN"), ...opts } = {}) { + _BaseGitLab_instances.add(this); + _BaseGitLab_encoder.set(this, void 0); + if (apiToken === void 0) { + throw new GitLabError("The GITLAB_API_TOKEN environment variable is missing or empty; either provide it, or instantiate the GitLab client with an apiToken option, like new GitLab({ apiToken: 'My API Token' })."); } + const options = { + apiToken, + ...opts, + baseURL: baseURL || `https://gitlab.com/api/v4` + }; + this.baseURL = options.baseURL; + this.timeout = options.timeout ?? BaseGitLab2.DEFAULT_TIMEOUT; + this.logger = options.logger ?? console; + const defaultLogLevel = "warn"; + this.logLevel = defaultLogLevel; + this.logLevel = parseLogLevel3(options.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel3(readEnv3("GITLAB_LOG"), "process.env['GITLAB_LOG']", this) ?? defaultLogLevel; + this.fetchOptions = options.fetchOptions; + this.maxRetries = options.maxRetries ?? 2; + this.fetch = options.fetch ?? getDefaultFetch3(); + __classPrivateFieldSet3(this, _BaseGitLab_encoder, FallbackEncoder3, "f"); + this._options = options; + this.apiToken = apiToken; } - return super.equals(left, right, options); - } -}; -var lineDiff = new LineDiff(); -function diffLines(oldStr, newStr, options) { - return lineDiff.diff(oldStr, newStr, options); -} -function tokenize(value, options) { - if (options.stripTrailingCr) { - value = value.replace(/\r\n/g, "\n"); - } - const retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/); - if (!linesAndNewlines[linesAndNewlines.length - 1]) { - linesAndNewlines.pop(); - } - for (let i = 0; i < linesAndNewlines.length; i++) { - const line = linesAndNewlines[i]; - if (i % 2 && !options.newlineIsToken) { - retLines[retLines.length - 1] += line; - } else { - retLines.push(line); + /** + * Create a new client instance re-using the same options given to the current client with optional overriding. + */ + withOptions(options) { + const client = new this.constructor({ + ...this._options, + baseURL: this.baseURL, + maxRetries: this.maxRetries, + timeout: this.timeout, + logger: this.logger, + logLevel: this.logLevel, + fetch: this.fetch, + fetchOptions: this.fetchOptions, + apiToken: this.apiToken, + ...options + }); + return client; + } + /** + * Execute a GLQL (GitLab Query Language) query + */ + glql(body, options) { + return this.post("/glql", { body, ...options }); + } + /** + * This feature was introduced in GitLab 11.0. + */ + markdown(body, options) { + return this.post("/markdown", { body, ...options }); + } + /** + * This feature was introduced in GitLab 17.5. \ + * This feature is currently in an experimental state. \ + * This feature is behind the `allow_organization_creation` feature flag. \ + * In GitLab 18.3, feature flag changed to `organization_switching`. + */ + organizations(body, options) { + return this.post("/organizations", multipartFormRequestOptions({ body, ...options }, this)); + } + /** + * Return avatar url for a user + */ + retrieveAvatar(query, options) { + return this.get("/avatar", { query, ...options }); + } + /** + * Get a list of all deploy tokens across the GitLab instance. This endpoint + * requires administrator access. This feature was introduced in GitLab 12.9. + */ + retrieveDeployTokens(query = {}, options) { + return this.get("/deploy_tokens", { query, ...options }); + } + /** + * This feature was introduced in GitLab 17.9. It will be removed in 18.0. + */ + retrieveDiscoverCertBasedClusters(query, options) { + return this.get("/discover-cert-based-clusters", { query, ...options }); + } + /** + * This feature was introduced in GitLab 9.3. + */ + retrieveEvents(query = {}, options) { + return this.get("/events", { query, ...options }); + } + /** + * Get a list of all experiments. Each experiment has an enabled status that + * indicates whetherthe experiment is enabled globally, or only in specific + * contexts. + */ + retrieveExperiments(options) { + return this.get("/experiments", options); } - } - return retLines; -} - -// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/line-endings.js -function unixToWin(patch) { - if (Array.isArray(patch)) { - return patch.map((p) => unixToWin(p)); - } - return Object.assign(Object.assign({}, patch), { hunks: patch.hunks.map((hunk) => Object.assign(Object.assign({}, hunk), { lines: hunk.lines.map((line, i) => { - var _a2; - return line.startsWith("\\") || line.endsWith("\r") || ((_a2 = hunk.lines[i + 1]) === null || _a2 === void 0 ? void 0 : _a2.startsWith("\\")) ? line : line + "\r"; - }) })) }); -} -function winToUnix(patch) { - if (Array.isArray(patch)) { - return patch.map((p) => winToUnix(p)); - } - return Object.assign(Object.assign({}, patch), { hunks: patch.hunks.map((hunk) => Object.assign(Object.assign({}, hunk), { lines: hunk.lines.map((line) => line.endsWith("\r") ? line.substring(0, line.length - 1) : line) })) }); -} -function isUnix(patch) { - if (!Array.isArray(patch)) { - patch = [patch]; - } - return !patch.some((index) => index.hunks.some((hunk) => hunk.lines.some((line) => !line.startsWith("\\") && line.endsWith("\r")))); -} -function isWin(patch) { - if (!Array.isArray(patch)) { - patch = [patch]; - } - return patch.some((index) => index.hunks.some((hunk) => hunk.lines.some((line) => line.endsWith("\r")))) && patch.every((index) => index.hunks.every((hunk) => hunk.lines.every((line, i) => { - var _a2; - return line.startsWith("\\") || line.endsWith("\r") || ((_a2 = hunk.lines[i + 1]) === null || _a2 === void 0 ? void 0 : _a2.startsWith("\\")); - }))); -} - -// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/parse.js -function parsePatch(uniDiff) { - const diffstr = uniDiff.split(/\n/), list = []; - let i = 0; - function parseIndex() { - const index = {}; - list.push(index); - while (i < diffstr.length) { - const line = diffstr[i]; - if (/^(---|\+\+\+|@@)\s/.test(line)) { - break; - } - const headerMatch = /^(?:Index:|diff(?: -r \w+)+)\s+/.exec(line); - if (headerMatch) { - index.index = line.substring(headerMatch[0].length).trim(); - } - i++; + /** + * Get currently authenticated user's issues statistics + */ + retrieveIssuesStatistics(query = {}, options) { + return this.get("/issues_statistics", { + query, + ...options, + headers: buildHeaders3([{ Accept: "*/*" }, options?.headers]) + }); } - parseFileHeader(index); - parseFileHeader(index); - index.hunks = []; - while (i < diffstr.length) { - const line = diffstr[i]; - if (/^(Index:\s|diff\s|---\s|\+\+\+\s|===================================================================)/.test(line)) { - break; - } else if (/^@@/.test(line)) { - index.hunks.push(parseHunk()); - } else if (line) { - throw new Error("Unknown line " + (i + 1) + " " + JSON.stringify(line)); - } else { - i++; - } + /** + * Get a list of licenses + */ + retrieveLicenses(options) { + return this.get("/licenses", options); } - } - function parseFileHeader(index) { - const fileHeaderMatch = /^(---|\+\+\+)\s+/.exec(diffstr[i]); - if (fileHeaderMatch) { - const prefix = fileHeaderMatch[1], data = diffstr[i].substring(3).trim().split(" ", 2), header = (data[1] || "").trim(); - let fileName = data[0].replace(/\\\\/g, "\\"); - if (fileName.startsWith('"') && fileName.endsWith('"')) { - fileName = fileName.substr(1, fileName.length - 2); - } - if (prefix === "---") { - index.oldFileName = fileName; - index.oldHeader = header; - } else { - index.newFileName = fileName; - index.newHeader = header; - } - i++; + /** + * Get all merge requests the authenticated user has access to. By default it + * returns only merge requests created by the current user. To get all merge + * requests, use parameter `scope=all`. + */ + retrieveMergeRequests(query = {}, options) { + return this.get("/merge_requests", { query, ...options }); } - } - function parseHunk() { - var _a2; - const chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); - const hunk = { - oldStart: +chunkHeader[1], - oldLines: typeof chunkHeader[2] === "undefined" ? 1 : +chunkHeader[2], - newStart: +chunkHeader[3], - newLines: typeof chunkHeader[4] === "undefined" ? 1 : +chunkHeader[4], - lines: [] - }; - if (hunk.oldLines === 0) { - hunk.oldStart += 1; + /** + * This feature was introduced in GitLab 15.2. + */ + retrieveMetadata(options) { + return this.get("/metadata", options); } - if (hunk.newLines === 0) { - hunk.newStart += 1; + /** + * This feature was introduced in GitLab 10.5. + */ + retrieveSearch(query, options) { + return this.get("/search", { + query, + ...options, + headers: buildHeaders3([{ Accept: "*/*" }, options?.headers]) + }); } - let addCount = 0, removeCount = 0; - for (; i < diffstr.length && (removeCount < hunk.oldLines || addCount < hunk.newLines || ((_a2 = diffstr[i]) === null || _a2 === void 0 ? void 0 : _a2.startsWith("\\"))); i++) { - const operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? " " : diffstr[i][0]; - if (operation === "+" || operation === "-" || operation === " " || operation === "\\") { - hunk.lines.push(diffstr[i]); - if (operation === "+") { - addCount++; - } else if (operation === "-") { - removeCount++; - } else if (operation === " ") { - addCount++; - removeCount++; - } - } else { - throw new Error(`Hunk at line ${chunkHeaderIndex + 1} contained invalid line ${diffstr[i]}`); - } + /** + * Assigned open issues, assigned MRs and pending todos count + */ + retrieveUserCounts(options) { + return this.get("/user_counts", options); } - if (!addCount && hunk.newLines === 1) { - hunk.newLines = 0; + /** + * This feature was introduced in GitLab 8.13 and deprecated in 15.5. We recommend + * you instead use the Metadata API. + */ + retrieveVersion(options) { + return this.get("/version", options); } - if (!removeCount && hunk.oldLines === 1) { - hunk.oldLines = 0; + defaultQuery() { + return this._options.defaultQuery; } - if (addCount !== hunk.newLines) { - throw new Error("Added line count did not match for hunk at line " + (chunkHeaderIndex + 1)); + validateHeaders({ values, nulls }) { + return; } - if (removeCount !== hunk.oldLines) { - throw new Error("Removed line count did not match for hunk at line " + (chunkHeaderIndex + 1)); + async authHeaders(opts) { + return buildHeaders3([{ Authorization: `Bearer ${this.apiToken}` }]); } - return hunk; - } - while (i < diffstr.length) { - parseIndex(); - } - return list; -} - -// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/util/distance-iterator.js -function distance_iterator_default(start, minLine, maxLine) { - let wantForward = true, backwardExhausted = false, forwardExhausted = false, localOffset = 1; - return function iterator() { - if (wantForward && !forwardExhausted) { - if (backwardExhausted) { - localOffset++; - } else { - wantForward = false; - } - if (start + localOffset <= maxLine) { - return start + localOffset; - } - forwardExhausted = true; + stringifyQuery(query) { + return stringify3(query, { arrayFormat: "comma" }); } - if (!backwardExhausted) { - if (!forwardExhausted) { - wantForward = true; - } - if (minLine <= start - localOffset) { - return start - localOffset++; - } - backwardExhausted = true; - return iterator(); + getUserAgent() { + return `${this.constructor.name}/JS ${VERSION3}`; } - return void 0; - }; -} - -// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/apply.js -function applyPatch(source, patch, options = {}) { - let patches; - if (typeof patch === "string") { - patches = parsePatch(patch); - } else if (Array.isArray(patch)) { - patches = patch; - } else { - patches = [patch]; - } - if (patches.length > 1) { - throw new Error("applyPatch only works with a single input."); - } - return applyStructuredPatch(source, patches[0], options); -} -function applyStructuredPatch(source, patch, options = {}) { - if (options.autoConvertLineEndings || options.autoConvertLineEndings == null) { - if (hasOnlyWinLineEndings(source) && isUnix(patch)) { - patch = unixToWin(patch); - } else if (hasOnlyUnixLineEndings(source) && isWin(patch)) { - patch = winToUnix(patch); + defaultIdempotencyKey() { + return `stainless-node-retry-${uuid43()}`; } - } - const lines = source.split("\n"), hunks = patch.hunks, compareLine = options.compareLine || ((lineNumber, line, operation, patchContent) => line === patchContent), fuzzFactor = options.fuzzFactor || 0; - let minLine = 0; - if (fuzzFactor < 0 || !Number.isInteger(fuzzFactor)) { - throw new Error("fuzzFactor must be a non-negative integer"); - } - if (!hunks.length) { - return source; - } - let prevLine = "", removeEOFNL = false, addEOFNL = false; - for (let i = 0; i < hunks[hunks.length - 1].lines.length; i++) { - const line = hunks[hunks.length - 1].lines[i]; - if (line[0] == "\\") { - if (prevLine[0] == "+") { - removeEOFNL = true; - } else if (prevLine[0] == "-") { - addEOFNL = true; - } + makeStatusError(status, error, message, headers) { + return APIError3.generate(status, error, message, headers); } - prevLine = line; - } - if (removeEOFNL) { - if (addEOFNL) { - if (!fuzzFactor && lines[lines.length - 1] == "") { - return false; + buildURL(path7, query, defaultBaseURL) { + const baseURL = !__classPrivateFieldGet3(this, _BaseGitLab_instances, "m", _BaseGitLab_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL; + const url = isAbsoluteURL3(path7) ? new URL(path7) : new URL(baseURL + (baseURL.endsWith("/") && path7.startsWith("/") ? path7.slice(1) : path7)); + const defaultQuery = this.defaultQuery(); + if (!isEmptyObj3(defaultQuery)) { + query = { ...defaultQuery, ...query }; } - } else if (lines[lines.length - 1] == "") { - lines.pop(); - } else if (!fuzzFactor) { - return false; + if (typeof query === "object" && query && !Array.isArray(query)) { + url.search = this.stringifyQuery(query); + } + return url.toString(); } - } else if (addEOFNL) { - if (lines[lines.length - 1] != "") { - lines.push(""); - } else if (!fuzzFactor) { - return false; + /** + * Used as a callback for mutating the given `FinalRequestOptions` object. + */ + async prepareOptions(options) { } - } - function applyHunk(hunkLines, toPos, maxErrors, hunkLinesI = 0, lastContextLineMatched = true, patchedLines = [], patchedLinesLength = 0) { - let nConsecutiveOldContextLines = 0; - let nextContextLineMustMatch = false; - for (; hunkLinesI < hunkLines.length; hunkLinesI++) { - const hunkLine = hunkLines[hunkLinesI], operation = hunkLine.length > 0 ? hunkLine[0] : " ", content = hunkLine.length > 0 ? hunkLine.substr(1) : hunkLine; - if (operation === "-") { - if (compareLine(toPos + 1, lines[toPos], operation, content)) { - toPos++; - nConsecutiveOldContextLines = 0; - } else { - if (!maxErrors || lines[toPos] == null) { - return null; - } - patchedLines[patchedLinesLength] = lines[toPos]; - return applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1); - } + /** + * Used as a callback for mutating the given `RequestInit` object. + * + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. + */ + async prepareRequest(request, { url, options }) { + } + get(path7, opts) { + return this.methodRequest("get", path7, opts); + } + post(path7, opts) { + return this.methodRequest("post", path7, opts); + } + patch(path7, opts) { + return this.methodRequest("patch", path7, opts); + } + put(path7, opts) { + return this.methodRequest("put", path7, opts); + } + delete(path7, opts) { + return this.methodRequest("delete", path7, opts); + } + methodRequest(method, path7, opts) { + return this.request(Promise.resolve(opts).then((opts2) => { + return { method, path: path7, ...opts2 }; + })); + } + request(options, remainingRetries = null) { + return new APIPromise3(this, this.makeRequest(options, remainingRetries, void 0)); + } + async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { + const options = await optionsInput; + const maxRetries = options.maxRetries ?? this.maxRetries; + if (retriesRemaining == null) { + retriesRemaining = maxRetries; } - if (operation === "+") { - if (!lastContextLineMatched) { - return null; - } - patchedLines[patchedLinesLength] = content; - patchedLinesLength++; - nConsecutiveOldContextLines = 0; - nextContextLineMustMatch = true; + await this.prepareOptions(options); + const { req, url, timeout } = await this.buildRequest(options, { + retryCount: maxRetries - retriesRemaining + }); + await this.prepareRequest(req, { url, options }); + const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0"); + const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`; + const startTime = Date.now(); + loggerFor3(this).debug(`[${requestLogID}] sending request`, formatRequestDetails3({ + retryOfRequestLogID, + method: options.method, + url, + options, + headers: req.headers + })); + if (options.signal?.aborted) { + throw new APIUserAbortError3(); } - if (operation === " ") { - nConsecutiveOldContextLines++; - patchedLines[patchedLinesLength] = lines[toPos]; - if (compareLine(toPos + 1, lines[toPos], operation, content)) { - patchedLinesLength++; - lastContextLineMatched = true; - nextContextLineMustMatch = false; - toPos++; - } else { - if (nextContextLineMustMatch || !maxErrors) { - return null; - } - return lines[toPos] && (applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI + 1, false, patchedLines, patchedLinesLength + 1) || applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1)) || applyHunk(hunkLines, toPos, maxErrors - 1, hunkLinesI + 1, false, patchedLines, patchedLinesLength); + const controller = new AbortController(); + const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError3); + const headersTime = Date.now(); + if (response instanceof globalThis.Error) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + if (options.signal?.aborted) { + throw new APIUserAbortError3(); } - } - } - patchedLinesLength -= nConsecutiveOldContextLines; - toPos -= nConsecutiveOldContextLines; - patchedLines.length = patchedLinesLength; - return { - patchedLines, - oldLineLastI: toPos - 1 - }; - } - const resultLines = []; - let prevHunkOffset = 0; - for (let i = 0; i < hunks.length; i++) { - const hunk = hunks[i]; - let hunkResult; - const maxLine = lines.length - hunk.oldLines + fuzzFactor; - let toPos; - for (let maxErrors = 0; maxErrors <= fuzzFactor; maxErrors++) { - toPos = hunk.oldStart + prevHunkOffset - 1; - const iterator = distance_iterator_default(toPos, minLine, maxLine); - for (; toPos !== void 0; toPos = iterator()) { - hunkResult = applyHunk(hunk.lines, toPos, maxErrors); - if (hunkResult) { - break; + const isTimeout = isAbortError3(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : "")); + if (retriesRemaining) { + loggerFor3(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`); + loggerFor3(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails3({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); } + loggerFor3(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`); + loggerFor3(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails3({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + if (isTimeout) { + throw new APIConnectionTimeoutError3(); + } + throw new APIConnectionError3({ cause: response }); } - if (hunkResult) { - break; + const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`; + if (!response.ok) { + const shouldRetry = await this.shouldRetry(response); + if (retriesRemaining && shouldRetry) { + const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`; + await CancelReadableStream3(response.body); + loggerFor3(this).info(`${responseInfo} - ${retryMessage2}`); + loggerFor3(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails3({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); + } + const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; + loggerFor3(this).info(`${responseInfo} - ${retryMessage}`); + const errText = await response.text().catch((err2) => castToError3(err2).message); + const errJSON = safeJSON3(errText); + const errMessage = errJSON ? void 0 : errText; + loggerFor3(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails3({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + message: errMessage, + durationMs: Date.now() - startTime + })); + const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); + throw err; } + loggerFor3(this).info(responseInfo); + loggerFor3(this).debug(`[${requestLogID}] response start`, formatRequestDetails3({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; } - if (!hunkResult) { - return false; - } - for (let i2 = minLine; i2 < toPos; i2++) { - resultLines.push(lines[i2]); - } - for (let i2 = 0; i2 < hunkResult.patchedLines.length; i2++) { - const line = hunkResult.patchedLines[i2]; - resultLines.push(line); - } - minLine = hunkResult.oldLineLastI + 1; - prevHunkOffset = toPos + 1 - hunk.oldStart; - } - for (let i = minLine; i < lines.length; i++) { - resultLines.push(lines[i]); - } - return resultLines.join("\n"); -} - -// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js -var INCLUDE_HEADERS = { - includeIndex: true, - includeUnderline: true, - includeFileHeaders: true -}; -function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { - let optionsObj; - if (!options) { - optionsObj = {}; - } else if (typeof options === "function") { - optionsObj = { callback: options }; - } else { - optionsObj = options; - } - if (typeof optionsObj.context === "undefined") { - optionsObj.context = 4; - } - const context = optionsObj.context; - if (optionsObj.newlineIsToken) { - throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions"); - } - if (!optionsObj.callback) { - return diffLinesResultToPatch(diffLines(oldStr, newStr, optionsObj)); - } else { - const { callback } = optionsObj; - diffLines(oldStr, newStr, Object.assign(Object.assign({}, optionsObj), { callback: (diff) => { - const patch = diffLinesResultToPatch(diff); - callback(patch); - } })); - } - function diffLinesResultToPatch(diff) { - if (!diff) { - return; + async fetchWithTimeout(url, init, ms, controller) { + const { signal, method, ...options } = init || {}; + const abort = this._makeAbort(controller); + if (signal) + signal.addEventListener("abort", abort, { once: true }); + const timeout = setTimeout(abort, ms); + const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body; + const fetchOptions = { + signal: controller.signal, + ...isReadableBody ? { duplex: "half" } : {}, + method: "GET", + ...options + }; + if (method) { + fetchOptions.method = method.toUpperCase(); + } + try { + return await this.fetch.call(void 0, url, fetchOptions); + } finally { + clearTimeout(timeout); + } } - diff.push({ value: "", lines: [] }); - function contextLines(lines) { - return lines.map(function(entry) { - return " " + entry; - }); + async shouldRetry(response) { + const shouldRetryHeader = response.headers.get("x-should-retry"); + if (shouldRetryHeader === "true") + return true; + if (shouldRetryHeader === "false") + return false; + if (response.status === 408) + return true; + if (response.status === 409) + return true; + if (response.status === 429) + return true; + if (response.status >= 500) + return true; + return false; } - const hunks = []; - let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; - for (let i = 0; i < diff.length; i++) { - const current = diff[i], lines = current.lines || splitLines(current.value); - current.lines = lines; - if (current.added || current.removed) { - if (!oldRangeStart) { - const prev = diff[i - 1]; - oldRangeStart = oldLine; - newRangeStart = newLine; - if (prev) { - curRange = context > 0 ? contextLines(prev.lines.slice(-context)) : []; - oldRangeStart -= curRange.length; - newRangeStart -= curRange.length; - } - } - for (const line of lines) { - curRange.push((current.added ? "+" : "-") + line); - } - if (current.added) { - newLine += lines.length; - } else { - oldLine += lines.length; - } - } else { - if (oldRangeStart) { - if (lines.length <= context * 2 && i < diff.length - 2) { - for (const line of contextLines(lines)) { - curRange.push(line); - } - } else { - const contextSize = Math.min(lines.length, context); - for (const line of contextLines(lines.slice(0, contextSize))) { - curRange.push(line); - } - const hunk = { - oldStart: oldRangeStart, - oldLines: oldLine - oldRangeStart + contextSize, - newStart: newRangeStart, - newLines: newLine - newRangeStart + contextSize, - lines: curRange - }; - hunks.push(hunk); - oldRangeStart = 0; - newRangeStart = 0; - curRange = []; - } + async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { + let timeoutMillis; + const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms"); + if (retryAfterMillisHeader) { + const timeoutMs = parseFloat(retryAfterMillisHeader); + if (!Number.isNaN(timeoutMs)) { + timeoutMillis = timeoutMs; } - oldLine += lines.length; - newLine += lines.length; } - } - for (const hunk of hunks) { - for (let i = 0; i < hunk.lines.length; i++) { - if (hunk.lines[i].endsWith("\n")) { - hunk.lines[i] = hunk.lines[i].slice(0, -1); + const retryAfterHeader = responseHeaders?.get("retry-after"); + if (retryAfterHeader && !timeoutMillis) { + const timeoutSeconds = parseFloat(retryAfterHeader); + if (!Number.isNaN(timeoutSeconds)) { + timeoutMillis = timeoutSeconds * 1e3; } else { - hunk.lines.splice(i + 1, 0, "\\ No newline at end of file"); - i++; + timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); } } + if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1e3)) { + const maxRetries = options.maxRetries ?? this.maxRetries; + timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + } + await sleep3(timeoutMillis); + return this.makeRequest(options, retriesRemaining - 1, requestLogID); } - return { - oldFileName, - newFileName, - oldHeader, - newHeader, - hunks - }; - } -} -function formatPatch(patch, headerOptions) { - if (!headerOptions) { - headerOptions = INCLUDE_HEADERS; - } - if (Array.isArray(patch)) { - if (patch.length > 1 && !headerOptions.includeFileHeaders) { - throw new Error("Cannot omit file headers on a multi-file patch. (The result would be unparseable; how would a tool trying to apply the patch know which changes are to which file?)"); + calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { + const initialRetryDelay = 0.5; + const maxRetryDelay = 8; + const numRetries = maxRetries - retriesRemaining; + const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); + const jitter = 1 - Math.random() * 0.25; + return sleepSeconds * jitter * 1e3; } - return patch.map((p) => formatPatch(p, headerOptions)).join("\n"); - } - const ret = []; - if (headerOptions.includeIndex && patch.oldFileName == patch.newFileName) { - ret.push("Index: " + patch.oldFileName); - } - if (headerOptions.includeUnderline) { - ret.push("==================================================================="); - } - if (headerOptions.includeFileHeaders) { - ret.push("--- " + patch.oldFileName + (typeof patch.oldHeader === "undefined" ? "" : " " + patch.oldHeader)); - ret.push("+++ " + patch.newFileName + (typeof patch.newHeader === "undefined" ? "" : " " + patch.newHeader)); - } - for (let i = 0; i < patch.hunks.length; i++) { - const hunk = patch.hunks[i]; - if (hunk.oldLines === 0) { - hunk.oldStart -= 1; + async buildRequest(inputOptions, { retryCount = 0 } = {}) { + const options = { ...inputOptions }; + const { method, path: path7, query, defaultBaseURL } = options; + const url = this.buildURL(path7, query, defaultBaseURL); + if ("timeout" in options) + validatePositiveInteger3("timeout", options.timeout); + options.timeout = options.timeout ?? this.timeout; + const { bodyHeaders, body } = this.buildBody({ options }); + const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); + const req = { + method, + headers: reqHeaders, + ...options.signal && { signal: options.signal }, + ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" }, + ...body && { body }, + ...this.fetchOptions ?? {}, + ...options.fetchOptions ?? {} + }; + return { req, url, timeout: options.timeout }; } - if (hunk.newLines === 0) { - hunk.newStart -= 1; + async buildHeaders({ options, method, bodyHeaders, retryCount }) { + let idempotencyHeaders = {}; + if (this.idempotencyHeader && method !== "get") { + if (!options.idempotencyKey) + options.idempotencyKey = this.defaultIdempotencyKey(); + idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; + } + const headers = buildHeaders3([ + idempotencyHeaders, + { + Accept: "application/json", + "User-Agent": this.getUserAgent(), + "X-Stainless-Retry-Count": String(retryCount), + ...options.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options.timeout / 1e3)) } : {}, + ...getPlatformHeaders3() + }, + await this.authHeaders(options), + this._options.defaultHeaders, + bodyHeaders, + options.headers + ]); + this.validateHeaders(headers); + return headers.values; } - ret.push("@@ -" + hunk.oldStart + "," + hunk.oldLines + " +" + hunk.newStart + "," + hunk.newLines + " @@"); - for (const line of hunk.lines) { - ret.push(line); + _makeAbort(controller) { + return () => controller.abort(); + } + buildBody({ options: { body, headers: rawHeaders } }) { + if (!body) { + return { bodyHeaders: void 0, body: void 0 }; + } + const headers = buildHeaders3([rawHeaders]); + if ( + // Pass raw type verbatim + ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && // Preserve legacy string encoding behavior for now + headers.values.has("content-type") || // `Blob` is superset of `File` + globalThis.Blob && body instanceof globalThis.Blob || // `FormData` -> `multipart/form-data` + body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded` + body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`) + globalThis.ReadableStream && body instanceof globalThis.ReadableStream + ) { + return { bodyHeaders: void 0, body }; + } else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) { + return { bodyHeaders: void 0, body: ReadableStreamFrom3(body) }; + } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") { + return { + bodyHeaders: { "content-type": "application/x-www-form-urlencoded" }, + body: this.stringifyQuery(body) + }; + } else { + return __classPrivateFieldGet3(this, _BaseGitLab_encoder, "f").call(this, { body, headers }); + } } } - return ret.join("\n") + "\n"; -} -function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { - if (typeof options === "function") { - options = { callback: options }; - } - if (!(options === null || options === void 0 ? void 0 : options.callback)) { - const patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); - if (!patchObj) { - return; + _BaseGitLab_encoder = /* @__PURE__ */ new WeakMap(), _BaseGitLab_instances = /* @__PURE__ */ new WeakSet(), _BaseGitLab_baseURLOverridden = function _BaseGitLab_baseURLOverridden2() { + return this.baseURL !== "https://gitlab.com/api/v4"; + }; + BaseGitLab2.DEFAULT_TIMEOUT = 6e4; + return BaseGitLab2; +})(); + +// node_modules/.pnpm/@stainless-api+gitlab-internal@0.3.0/node_modules/@stainless-api/gitlab-internal/tree-shakable.mjs +function createClient2(options) { + const client = new BaseGitLab(options); + for (const ResourceClass of options.resources) { + const resourceInstance = new ResourceClass(client); + let object = client; + for (const part of ResourceClass._key.slice(0, -1)) { + if (hasOwn3(object, part)) { + object = object[part]; + } else { + Object.defineProperty(object, part, { + value: object = {}, + configurable: true, + enumerable: true, + writable: true + }); + } } - return formatPatch(patchObj, options === null || options === void 0 ? void 0 : options.headerOptions); - } else { - const { callback } = options; - structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, Object.assign(Object.assign({}, options), { callback: (patchObj) => { - if (!patchObj) { - callback(void 0); + const name = ResourceClass._key.at(-1); + if (!hasOwn3(object, name)) { + Object.defineProperty(object, name, { + value: resourceInstance, + configurable: true, + enumerable: true, + writable: true + }); + } else { + if (object[name] instanceof APIResource3) { + throw new TypeError(`Resource at ${ResourceClass._key.join(".")} already exists!`); } else { - callback(formatPatch(patchObj, options.headerOptions)); + object[name] = Object.assign(resourceInstance, object[name]); } - } })); - } -} -function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { - return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); -} -function splitLines(text) { - const hasTrailingNl = text.endsWith("\n"); - const result = text.split("\n").map((line) => line + "\n"); - if (hasTrailingNl) { - result.pop(); - } else { - result.push(result.pop().slice(0, -1)); + } } - return result; + return client; } -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/tslib.mjs -function __classPrivateFieldSet3(receiver, state, value, kind, f) { - if (kind === "m") - throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) - throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) - throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; -} -function __classPrivateFieldGet3(receiver, state, kind, f) { - if (kind === "a" && !f) - throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) - throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +// src/compat/gitlab/context.ts +var cachedContext2; +function getGitLabContext() { + if (cachedContext2) { + return cachedContext2; + } + const owner = process.env.CI_PROJECT_NAMESPACE; + const repo = process.env.CI_PROJECT_NAME; + const runURL = process.env.CI_JOB_URL; + const projectID = process.env.CI_PROJECT_ID; + if (!owner || !repo || !runURL || !projectID) { + throw new Error( + "Expected env vars CI_PROJECT_NAMESPACE, CI_PROJECT_NAME, CI_JOB_URL, and CI_PROJECT_ID to be set." + ); + } + const host = process.env.CI_SERVER_URL || "https://gitlab.com"; + const apiURL = process.env.CI_API_V4_URL || `${host}/api/v4`; + const maybePRNumber = parseInt( + process.env.CI_MERGE_REQUEST_IID || process.env.MR_NUMBER || "", + 10 + ); + const defaultBranch = process.env.CI_DEFAULT_BRANCH || null; + const prNumber = Number.isInteger(maybePRNumber) ? maybePRNumber : null; + const refName = process.env.CI_COMMIT_REF_NAME || null; + const sha = process.env.CI_COMMIT_SHA || null; + cachedContext2 = { + provider: "gitlab", + host, + owner, + repo, + urls: { api: apiURL, run: runURL }, + names: { ci: "GitLab CI", pr: "MR", provider: "GitLab" }, + defaultBranch, + prNumber, + projectID, + refName, + sha + }; + logger.debug("GitLab context", cachedContext2); + return cachedContext2; } -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/uuid.mjs -var uuid43 = function() { - const { crypto: crypto2 } = globalThis; - if (crypto2?.randomUUID) { - uuid43 = crypto2.randomUUID.bind(crypto2); - return crypto2.randomUUID(); +// src/compat/gitlab/api.ts +var GitLabClient = class { + client; + constructor(token) { + this.client = createClient2({ + apiToken: token, + baseURL: getGitLabContext().urls.api, + resources: [BaseCommits3, BaseMergeRequests, BaseNotes2], + logLevel: "warn", + logger + }); } - const u8 = new Uint8Array(1); - const randomByte = crypto2 ? () => crypto2.getRandomValues(u8)[0] : () => Math.random() * 255 & 255; - return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16)); -}; - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/errors.mjs -function isAbortError3(err) { - return typeof err === "object" && err !== null && // Spec-compliant fetch implementations - ("name" in err && err.name === "AbortError" || // Expo fetch - "message" in err && String(err.message).includes("FetchRequestCanceledException")); -} -var castToError3 = (err) => { - if (err instanceof Error) - return err; - if (typeof err === "object" && err !== null) { - try { - if (Object.prototype.toString.call(err) === "[object Error]") { - const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); - if (err.stack) - error.stack = err.stack; - if (err.cause && !error.cause) - error.cause = err.cause; - if (err.name) - error.name = err.name; - return error; + async listComments(prNumber) { + const comments = await this.client.projects.mergeRequests.notes.list(prNumber, { id: getGitLabContext().projectID }).then((data) => Array.isArray(data) ? data : [data]).catch((err) => { + if (err instanceof APIError3 && err.status === 404) { + return []; } - } catch { - } - try { - return new Error(JSON.stringify(err)); - } catch { - } + throw err; + }); + return comments.map((c) => ({ id: c.id, body: c.body ?? "" })); } - return new Error(err); -}; - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/core/error.mjs -var StainlessError = class extends Error { -}; -var APIError3 = class _APIError extends StainlessError { - constructor(status, error, message, headers) { - super(`${_APIError.makeMessage(status, error, message)}`); - this.status = status; - this.headers = headers; - this.error = error; + async createComment(prNumber, props) { + const data = await this.client.projects.mergeRequests.notes.create( + prNumber, + { ...props, id: getGitLabContext().projectID } + ); + return { id: data.id, body: data.body }; } - static makeMessage(status, error, message) { - const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message; - if (status && msg) { - return `${status} ${msg}`; - } - if (status) { - return `${status} status code (no body)`; - } - if (msg) { - return msg; - } - return "(no status code or body)"; + async updateComment(prNumber, props) { + const data = await this.client.projects.mergeRequests.notes.update( + props.id, + { ...props, id: getGitLabContext().projectID, noteable_id: prNumber } + ); + return { id: data.id, body: data.body }; } - static generate(status, errorResponse, message, headers) { - if (!status || !headers) { - return new APIConnectionError3({ message, cause: castToError3(errorResponse) }); - } - const error = errorResponse; - if (status === 400) { - return new BadRequestError3(status, error, message, headers); + async getPullRequest(number) { + let mergeRequest = null; + let attempts = 0; + while (attempts++ < 3) { + mergeRequest = await this.client.projects.mergeRequests.retrieve(number, { + id: getGitLabContext().projectID + }); + if (mergeRequest?.diff_refs?.start_sha && mergeRequest?.diff_refs?.head_sha) { + return { + number: mergeRequest.iid, + state: mergeRequest.state === "opened" ? "open" : mergeRequest.state === "locked" ? "closed" : mergeRequest.state, + title: mergeRequest.title, + base_sha: mergeRequest.diff_refs.start_sha, + base_ref: mergeRequest.target_branch, + head_sha: mergeRequest.diff_refs.head_sha, + head_ref: mergeRequest.source_branch, + merge_commit_sha: mergeRequest.merge_commit_sha || mergeRequest.squash_commit_sha || null + }; + } + await new Promise((resolve) => { + setTimeout(() => resolve(), 1e3 * (2 ** attempts + Math.random())); + }); } - if (status === 401) { - return new AuthenticationError3(status, error, message, headers); + logger.warn( + `Failed to find get diff_refs for merge request after ${attempts} attempts`, + { mergeRequestIID: number } + ); + return null; + } + async getPullRequestForCommit(sha) { + const mergeRequests = await this.client.projects.repository.commits.retrieveMergeRequests(sha, { + id: getGitLabContext().projectID + }).then( + (data) => ( + // The OAS claims it's a single object, but the docs claim it's an + // array? Just handle both. + (Array.isArray(data) ? data : [data]).filter( + (c) => c.state !== "closed" && c.state !== "locked" + ) + ) + ).catch((err) => { + if (err instanceof APIError3 && (err.status === 401 || err.status === 403 || err.status === 404)) { + return []; + } + throw err; + }); + if (mergeRequests.length === 0) { + return null; } - if (status === 403) { - return new PermissionDeniedError3(status, error, message, headers); + if (mergeRequests.length > 1) { + logger.warn( + `Multiple merge requests found for commit; only using first.`, + { commit: sha, mergeRequests: mergeRequests.map((c) => c.iid) } + ); } - if (status === 404) { - return new NotFoundError3(status, error, message, headers); + const mergeRequestIID = mergeRequests[0].iid; + const mergeRequest = await this.getPullRequest(mergeRequestIID); + return mergeRequest; + } +}; +var cachedClient2; +function getGitLabClient() { + if (cachedClient2 !== void 0) { + return cachedClient2; + } + const token = getInput("GITLAB_TOKEN"); + if (token?.startsWith("$")) { + throw new Error( + `Input GITLAB_TOKEN starts with '$'; expected token to start with 'gl'. Does the CI have access to the variable?` + ); + } + if (token) { + cachedClient2 = new GitLabClient(token); + } else { + logger.info("No GitLab token found in input 'GITLAB_TOKEN'."); + cachedClient2 = null; + } + return cachedClient2; +} + +// src/compat/api.ts +function api(options) { + let client; + switch (getProvider()) { + case "github": { + client = getGitHubClient(); + break; } - if (status === 409) { - return new ConflictError3(status, error, message, headers); + case "gitlab": { + client = getGitLabClient(); + break; } - if (status === 422) { - return new UnprocessableEntityError3(status, error, message, headers); + } + if (!client) { + if (options?.optional) { + return null; + } else { + throw new Error("Failed to get API client."); } - if (status === 429) { - return new RateLimitError3(status, error, message, headers); + } + return client; +} + +// src/compat/context.ts +function ctx() { + switch (getProvider()) { + case "github": { + return getGitHubContext(); } - if (status >= 500) { - return new InternalServerError3(status, error, message, headers); + case "gitlab": { + return getGitLabContext(); } - return new _APIError(status, error, message, headers); - } -}; -var APIUserAbortError3 = class extends APIError3 { - constructor({ message } = {}) { - super(void 0, void 0, message || "Request was aborted.", void 0); - } -}; -var APIConnectionError3 = class extends APIError3 { - constructor({ message, cause }) { - super(void 0, void 0, message || "Connection error.", void 0); - if (cause) - this.cause = cause; - } -}; -var APIConnectionTimeoutError3 = class extends APIConnectionError3 { - constructor({ message } = {}) { - super({ message: message ?? "Request timed out." }); } -}; -var BadRequestError3 = class extends APIError3 { -}; -var AuthenticationError3 = class extends APIError3 { -}; -var PermissionDeniedError3 = class extends APIError3 { -}; -var NotFoundError3 = class extends APIError3 { -}; -var ConflictError3 = class extends APIError3 { -}; -var UnprocessableEntityError3 = class extends APIError3 { -}; -var RateLimitError3 = class extends APIError3 { -}; -var InternalServerError3 = class extends APIError3 { -}; +} -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/values.mjs -var startsWithSchemeRegexp3 = /^[a-z][a-z0-9+.-]*:/i; -var isAbsoluteURL3 = (url) => { - return startsWithSchemeRegexp3.test(url); -}; -var isArray3 = (val) => (isArray3 = Array.isArray, isArray3(val)); -var isReadonlyArray3 = isArray3; -function maybeObj2(x) { - if (typeof x !== "object") { - return {}; +// src/compat/output.ts +var crypto = __toESM(require("node:crypto")); +var fs2 = __toESM(require("node:fs")); +function setOutput(name, value) { + if (getProvider() === "gitlab") return; + const stringified = value === null || value === void 0 ? "" : typeof value === "string" ? value : JSON.stringify(value); + const filePath = process.env["GITHUB_OUTPUT"]; + if (filePath && fs2.existsSync(filePath)) { + const delimiter = `ghadelimiter_${crypto.randomUUID()}`; + fs2.appendFileSync( + filePath, + `${name}<<${delimiter} +${stringified} +${delimiter} +`, + "utf-8" + ); + } else { + process.stdout.write(` +::set-output name=${name}::${stringified} +`); } - return x ?? {}; -} -function isEmptyObj3(obj) { - if (!obj) - return true; - for (const _k in obj) - return false; - return true; -} -function hasOwn3(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); } -var validatePositiveInteger3 = (name, n) => { - if (typeof n !== "number" || !Number.isInteger(n)) { - throw new StainlessError(`${name} must be an integer`); + +// src/compat/index.ts +async function getStainlessAuth() { + const apiKey = getInput("stainless_api_key", { + required: getProvider() === "gitlab" + }); + if (apiKey) { + logger.debug("Authenticating with provided Stainless API key"); + return { + key: apiKey, + expiresAt: null + }; } - if (n < 0) { - throw new StainlessError(`${name} must be a positive integer`); + logger.debug("Authenticating with GitHub OIDC"); + const requestUrl = process.env.ACTIONS_ID_TOKEN_REQUEST_URL; + const requestToken = process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN; + if (!requestUrl || !requestToken) { + throw new Error( + `Failed to authenticate with GitHub OIDC. Make sure your workflow has 'id-token: write' permission and that you have the Stainless GitHub App installed: https://www.stainless.com/docs/guides/publish/#install-the-stainless-github-app` + ); } - return n; -}; -var safeJSON3 = (text) => { try { - return JSON.parse(text); - } catch (err) { - return void 0; + const response = await fetch(`${requestUrl}&audience=api.stainless.com`, { + headers: { Authorization: `Bearer ${requestToken}` } + }); + if (!response.ok) { + throw new Error(`HTTP ${response.status}: ${await response.text()}`); + } + const data = await response.json(); + if (!data.value) { + throw new Error("No token in OIDC response"); + } + return { + key: data.value, + expiresAt: Date.now() + 300 * 1e3 + }; + } catch (error) { + throw new Error( + `Failed to authenticate with GitHub OIDC. Make sure your workflow has 'id-token: write' permission and that you have the Stainless GitHub App installed: https://www.stainless.com/docs/guides/publish/#install-the-stainless-github-app. Error: ${error}` + ); } -}; - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/sleep.mjs -var sleep3 = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/version.mjs -var VERSION3 = "0.5.0"; +} -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/detect-platform.mjs -function getDetectedPlatform3() { - if (typeof Deno !== "undefined" && Deno.build != null) { - return "deno"; +// src/outcomes.ts +var ASSUME_PENDING_CHECKS_SKIPPED_AFTER_SECS = 60; +var FailRunOn = [ + "never", + "fatal", + "error", + "warning", + "note" +]; +var OutcomeConclusion = [...FailRunOn, "success"]; +function shouldFailRun({ + failRunOn, + outcomes, + baseOutcomes +}) { + const failures = Object.entries(outcomes).flatMap(([language, outcome]) => { + const categorized = categorizeOutcome({ + outcome, + baseOutcome: baseOutcomes?.[language] + }); + if (categorized.isPending) { + return []; + } + const { severity, isRegression, description } = categorized; + const didFail = isRegression !== false && severity && OutcomeConclusion.indexOf(severity) <= OutcomeConclusion.indexOf(failRunOn); + return didFail ? [ + { + language, + reason: getReason({ + description, + isRegression + }) + } + ] : []; + }); + if (failures.length > 0) { + logger.warn("The following languages did not build successfully:"); + for (const { language, reason } of failures) { + logger.warn(` ${language}: ${reason}`); + } + return false; } - if (typeof EdgeRuntime !== "undefined") { - return "edge"; + return true; +} +function categorizeOutcome({ + outcome, + baseOutcome +}) { + const baseConclusion = baseOutcome?.commit?.conclusion; + const headConclusion = outcome.commit?.conclusion; + if (!headConclusion || baseOutcome && !baseConclusion) { + return { isPending: true }; } - if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") { - return "node"; + const baseChecks = baseOutcome && baseOutcome.commit?.commit ? getChecks(baseOutcome) : {}; + const headChecks = outcome.commit?.commit ? getChecks(outcome) : {}; + if ([...Object.values(headChecks), ...Object.values(baseChecks)].some( + (check) => check && check.status !== "completed" + )) { + return { isPending: true }; + } + const newDiagnostics = sortDiagnostics( + baseOutcome ? getNewDiagnostics(outcome.diagnostics, baseOutcome.diagnostics) : outcome.diagnostics + ); + const conclusions = { + fatal: [ + "fatal", + "payment_required", + "timed_out", + "upstream_merge_conflict", + "version_bump" + ], + conflict: ["merge_conflict"], + diagnostic: ["error", "warning", "note"], + success: ["success", "noop", "cancelled"] + }; + const checks = getNewChecks(headChecks, baseChecks); + const checkFailures = CheckType.filter( + (checkType) => checks[checkType] && checks[checkType].status === "completed" && ["failure", "timed_out"].includes(checks[checkType].completed.conclusion) + ); + if (headConclusion === "timed_out" || baseConclusion === "timed_out") { + return { + isPending: false, + conclusion: "timed_out", + severity: "fatal", + description: "timed out before completion", + isRegression: null + }; } - return "unknown"; -} -var getPlatformProperties3 = () => { - const detectedPlatform = getDetectedPlatform3(); - if (detectedPlatform === "deno") { + if (conclusions.fatal.includes(headConclusion)) { return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION3, - "X-Stainless-OS": normalizePlatform3(Deno.build.os), - "X-Stainless-Arch": normalizeArch3(Deno.build.arch), - "X-Stainless-Runtime": "deno", - "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown" + isPending: false, + conclusion: "fatal", + severity: "fatal", + description: `had a "${headConclusion}" conclusion, and no code was generated`, + isRegression: baseConclusion ? conclusions.fatal.includes(baseConclusion) ? false : true : null }; } - if (typeof EdgeRuntime !== "undefined") { + if (baseConclusion && conclusions.fatal.includes(baseConclusion)) { return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION3, - "X-Stainless-OS": "Unknown", - "X-Stainless-Arch": `other:${EdgeRuntime}`, - "X-Stainless-Runtime": "edge", - "X-Stainless-Runtime-Version": globalThis.process.version + isPending: false, + conclusion: headConclusion, + severity: null, + description: `had a "${baseOutcome?.commit?.conclusion}" conclusion in the base build, which improved to "${headConclusion}"`, + isRegression: false }; } - if (detectedPlatform === "node") { + if (conclusions.diagnostic.includes(headConclusion) || newDiagnostics.length > 0 || checkFailures.length > 0) { + const categoryOutcome = conclusions.diagnostic.includes(headConclusion) ? { + severity: headConclusion, + description: `had at least one "${headConclusion}" diagnostic`, + isRegression: baseConclusion ? conclusions.success.includes(baseConclusion) || conclusions.diagnostic.indexOf(headConclusion) < conclusions.diagnostic.indexOf(baseConclusion) ? true : false : null, + rank: 1 + } : null; + const diagnosticLevelOutcome = newDiagnostics.length > 0 ? { + severity: newDiagnostics[0].level, + description: `had at least one ${baseOutcome ? "new " : ""}${newDiagnostics[0].level} diagnostic`, + isRegression: baseOutcome ? true : null, + rank: 2 + } : null; + let checkFailureOutcome; + for (const { step, severity } of [ + { step: "build", severity: "error" }, + { step: "lint", severity: "warning" }, + { step: "test", severity: "warning" } + ]) { + if (checkFailures.includes(step)) { + checkFailureOutcome = { + severity, + description: `had a failure in the ${step} CI job`, + isRegression: baseChecks ? true : null, + rank: 3 + }; + break; + } + } + const worstOutcome = [ + categoryOutcome, + diagnosticLevelOutcome, + checkFailureOutcome + ].filter((r) => r !== null).sort( + (a, b) => ( + // sort by regression status then severity then rank + (!(a.severity === "fatal" || b.severity === "fatal") ? [true, null, false].indexOf(a.isRegression) - [true, null, false].indexOf(b.isRegression) : 0) || conclusions.diagnostic.indexOf(a.severity) - conclusions.diagnostic.indexOf(b.severity) || a.rank - b.rank + ) + )[0]; return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION3, - "X-Stainless-OS": normalizePlatform3(globalThis.process.platform ?? "unknown"), - "X-Stainless-Arch": normalizeArch3(globalThis.process.arch ?? "unknown"), - "X-Stainless-Runtime": "node", - "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown" + isPending: false, + conclusion: worstOutcome.severity, + ...worstOutcome }; } - const browserInfo = getBrowserInfo3(); - if (browserInfo) { + if (conclusions.conflict.includes(headConclusion)) { return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION3, - "X-Stainless-OS": "Unknown", - "X-Stainless-Arch": "unknown", - "X-Stainless-Runtime": `browser:${browserInfo.browser}`, - "X-Stainless-Runtime-Version": browserInfo.version + isPending: false, + conclusion: "merge_conflict", + severity: baseConclusion !== "merge_conflict" ? "warning" : null, + description: "resulted in a merge conflict between your custom code and the newly generated changes", + isRegression: baseConclusion ? baseConclusion !== "merge_conflict" ? true : false : null }; } return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION3, - "X-Stainless-OS": "Unknown", - "X-Stainless-Arch": "unknown", - "X-Stainless-Runtime": "unknown", - "X-Stainless-Runtime-Version": "unknown" + isPending: false, + conclusion: headConclusion, + severity: null, + description: headConclusion === "success" ? "was successful" : `had a conclusion of ${headConclusion}`, + isRegression: null }; -}; -function getBrowserInfo3() { - if (typeof navigator === "undefined" || !navigator) { - return null; - } - const browserPatterns = [ - { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ } - ]; - for (const { key, pattern } of browserPatterns) { - const match = pattern.exec(navigator.userAgent); - if (match) { - const major = match[1] || 0; - const minor = match[2] || 0; - const patch = match[3] || 0; - return { browser: key, version: `${major}.${minor}.${patch}` }; +} +function getReason({ + description, + isRegression +}) { + return `Your SDK build ${description}${isRegression === true ? ", which is a regression from the base state" : isRegression === false ? ", but this did not represent a regression" : ""}.`; +} +var DiagnosticLevel = ["fatal", "error", "warning", "note"]; +function countDiagnosticLevels(diagnostics) { + return diagnostics.reduce( + (counts, diag) => { + counts[diag.level] = (counts[diag.level] || 0) + 1; + return counts; + }, + { + fatal: 0, + error: 0, + warning: 0, + note: 0 } - } - return null; + ); } -var normalizeArch3 = (arch) => { - if (arch === "x32") - return "x32"; - if (arch === "x86_64" || arch === "x64") - return "x64"; - if (arch === "arm") - return "arm"; - if (arch === "aarch64" || arch === "arm64") - return "arm64"; - if (arch) - return `other:${arch}`; - return "unknown"; -}; -var normalizePlatform3 = (platform) => { - platform = platform.toLowerCase(); - if (platform.includes("ios")) - return "iOS"; - if (platform === "android") - return "Android"; - if (platform === "darwin") - return "MacOS"; - if (platform === "win32") - return "Windows"; - if (platform === "freebsd") - return "FreeBSD"; - if (platform === "openbsd") - return "OpenBSD"; - if (platform === "linux") - return "Linux"; - if (platform) - return `Other:${platform}`; - return "Unknown"; -}; -var _platformHeaders3; -var getPlatformHeaders3 = () => { - return _platformHeaders3 ?? (_platformHeaders3 = getPlatformProperties3()); -}; - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/shims.mjs -function getDefaultFetch3() { - if (typeof fetch !== "undefined") { - return fetch; +function getNewDiagnostics(diagnostics, baseDiagnostics) { + if (!baseDiagnostics) { + return diagnostics; } - throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Stainless({ fetch })` or polyfill the global, `globalThis.fetch = fetch`"); + return diagnostics.filter( + (d) => !baseDiagnostics.some( + (bd) => bd.code === d.code && bd.message === d.message && bd.config_ref === d.config_ref && bd.oas_ref === d.oas_ref + ) + ); } -function makeReadableStream3(...args) { - const ReadableStream = globalThis.ReadableStream; - if (typeof ReadableStream === "undefined") { - throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`"); +function sortDiagnostics(diagnostics) { + return diagnostics.sort( + (a, b) => DiagnosticLevel.indexOf(a.level) - DiagnosticLevel.indexOf(b.level) + ); +} +var CheckType = ["build", "lint", "test"]; +function getChecks(outcome) { + const results = {}; + const commitCompletedMoreThanXSecsAgo = outcome.commit ? (/* @__PURE__ */ new Date()).getTime() - new Date(outcome.commit.completed_at).getTime() > ASSUME_PENDING_CHECKS_SKIPPED_AFTER_SECS * 1e3 : false; + for (const checkType of CheckType) { + if (outcome[checkType]?.status === "not_started" && commitCompletedMoreThanXSecsAgo) { + outcome[checkType] = { + status: "completed", + conclusion: "skipped", + completed: { + conclusion: "skipped", + url: null + }, + url: null + }; + } + results[checkType] = outcome[checkType] || null; } - return new ReadableStream(...args); + return results; } -function ReadableStreamFrom3(iterable) { - let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); - return makeReadableStream3({ - start() { - }, - async pull(controller) { - const { done, value } = await iter.next(); - if (done) { - controller.close(); - } else { - controller.enqueue(value); - } - }, - async cancel() { - await iter.return?.(); +function getNewChecks(headChecks, baseChecks) { + const result = {}; + for (const checkType of CheckType) { + const headCheck = headChecks[checkType]; + const baseCheck = baseChecks ? baseChecks[checkType] : null; + if (headCheck) { + const baseConclusion = baseCheck?.status === "completed" && baseCheck.conclusion; + const conclusion = headCheck.status === "completed" && headCheck.conclusion; + if (!baseConclusion || baseConclusion !== conclusion) { + result[checkType] = headCheck; + } } - }); + } + return result; } -async function CancelReadableStream3(stream) { - if (stream === null || typeof stream !== "object") - return; - if (stream[Symbol.asyncIterator]) { - await stream[Symbol.asyncIterator]().return?.(); - return; + +// src/preview.run.ts +var fs5 = __toESM(require("node:fs")); + +// src/commitMessage.ts +var CONVENTIONAL_COMMIT_REGEX = new RegExp( + /^(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test)(\(.*\))?(!?): .*$/m +); +function makeCommitMessageConventional(message) { + if (message && !CONVENTIONAL_COMMIT_REGEX.test(message)) { + logger.warn( + `Commit message "${message}" is not in Conventional Commits format: https://www.conventionalcommits.org/en/v1.0.0/. Prepending "feat:" and using anyway.` + ); + return `feat: ${message}`; } - const reader = stream.getReader(); - const cancelPromise = reader.cancel(); - reader.releaseLock(); - await cancelPromise; + return message; } -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/request-options.mjs -var FallbackEncoder3 = ({ headers, body }) => { - return { - bodyHeaders: { - "content-type": "application/json" - }, - body: JSON.stringify(body) - }; +// src/markdown.ts +var import_ts_dedent = __toESM(require_dist()); +var Symbol2 = { + Bulb: "\u{1F4A1}", + Construction: "\u{1F6A7}", + Exclamation: "\u2757", + Eyes: "\u{1F440}", + GreenSquare: "\u{1F7E9}", + HeavyAsterisk: "\u2731", + HourglassFlowingSand: "\u23F3", + MiddleDot: "\xB7", + RedSquare: "\u{1F7E5}", + RightwardsArrow: "\u2192", + Skipped: "\u23ED\uFE0F", + SpeechBalloon: "\u{1F4AC}", + Warning: "\u26A0\uFE0F", + WhiteCheckMark: "\u2705", + WhiteLargeSquare: "\u2B1C", + Zap: "\u26A1" }; +var Bold = (content) => `${content}`; +var CodeInline = (content) => `${content}`; +var Comment = (content) => ``; +var Italic = (content) => `${content}`; +function Dedent(templ, ...args) { + return (0, import_ts_dedent.dedent)(templ, ...args).trim().replaceAll(/\n\s*\n/gi, "\n\n"); +} +var Blockquote = (content) => Dedent` +
-// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/qs/formats.mjs -var default_format3 = "RFC3986"; -var default_formatter3 = (v) => String(v); -var formatters3 = { - RFC1738: (v) => String(v).replace(/%20/g, "+"), - RFC3986: default_formatter3 + ${content} + +
+ `; +var CodeBlock = (props) => { + const delimiter = "```"; + const content = typeof props === "string" ? props : props.content; + const language = typeof props === "string" ? "" : props.language; + return Dedent` + ${delimiter}${language} + ${content} + ${delimiter} + `; }; -var RFC17383 = "RFC1738"; +var Details = ({ + summary, + body, + indent = true, + open = false +}) => { + return Dedent` + + ${summary} -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/qs/utils.mjs -var has3 = (obj, key) => (has3 = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has3(obj, key)); -var hex_table3 = /* @__PURE__ */ (() => { - const array = []; - for (let i = 0; i < 256; ++i) { - array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase()); - } - return array; -})(); -var limit3 = 1024; -var encode3 = (str, _defaultEncoder, charset, _kind, format) => { - if (str.length === 0) { - return str; - } - let string = str; - if (typeof str === "symbol") { - string = Symbol.prototype.toString.call(str); - } else if (typeof str !== "string") { - string = String(str); - } - if (charset === "iso-8859-1") { - return escape(string).replace(/%u[0-9a-f]{4}/gi, function($0) { - return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; - }); - } - let out = ""; - for (let j = 0; j < string.length; j += limit3) { - const segment = string.length >= limit3 ? string.slice(j, j + limit3) : string; - const arr = []; - for (let i = 0; i < segment.length; ++i) { - let c = segment.charCodeAt(i); - if (c === 45 || // - - c === 46 || // . - c === 95 || // _ - c === 126 || // ~ - c >= 48 && c <= 57 || // 0-9 - c >= 65 && c <= 90 || // a-z - c >= 97 && c <= 122 || // A-Z - format === RFC17383 && (c === 40 || c === 41)) { - arr[arr.length] = segment.charAt(i); - continue; - } - if (c < 128) { - arr[arr.length] = hex_table3[c]; - continue; - } - if (c < 2048) { - arr[arr.length] = hex_table3[192 | c >> 6] + hex_table3[128 | c & 63]; - continue; - } - if (c < 55296 || c >= 57344) { - arr[arr.length] = hex_table3[224 | c >> 12] + hex_table3[128 | c >> 6 & 63] + hex_table3[128 | c & 63]; - continue; - } - i += 1; - c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023); - arr[arr.length] = hex_table3[240 | c >> 18] + hex_table3[128 | c >> 12 & 63] + hex_table3[128 | c >> 6 & 63] + hex_table3[128 | c & 63]; - } - out += arr.join(""); - } - return out; + ${indent ? Blockquote(body) : body} + + + `; }; -function is_buffer3(obj) { - if (!obj || typeof obj !== "object") { - return false; - } - return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +var Heading = (content) => `

${content}

`; +var Link = ({ text, href }) => `${text}`; +var Rule = () => `
`; + +// src/comment.ts +var COMMENT_TITLE = Heading( + `${Symbol2.HeavyAsterisk} Stainless preview builds` +); +var COMMENT_FOOTER_DIVIDER = Comment("stainless-preview-footer"); +function printComment({ + noChanges, + orgName, + projectName, + branch, + commitMessage, + targetCommitMessages, + pendingAiCommitMessages, + baseOutcomes, + outcomes +}) { + const Blocks4 = (() => { + if (noChanges) { + return "No changes were made to the SDKs."; + } + const canEdit = !!baseOutcomes; + return [ + Dedent` + This ${ctx().names.pr} will update the ${CodeInline( + projectName + )} SDKs with the following commit ${targetCommitMessages ? "messages" : "message"}. + `, + targetCommitMessages ? CommitMessagesSection({ + targets: Object.keys(outcomes).sort(), + pendingAiCommitMessages, + targetCommitMessages, + commitMessage + }) : CodeBlock(commitMessage), + !canEdit ? null : targetCommitMessages ? "Edit this comment to update them. They will appear in their respective SDK's changelogs." : "Edit this comment to update it. It will appear in the SDK's changelogs.", + Results({ orgName, projectName, branch, outcomes, baseOutcomes }) + ].filter((f) => f !== null).join(` + +`); + })(); + const dateString = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").replace(/\.\d+Z$/, " UTC"); + const fullComment = Dedent` + ${COMMENT_TITLE} + + ${Blocks4} + + ${Rule()} + + ${COMMENT_FOOTER_DIVIDER} + + ${Italic( + `This comment is auto-generated by ${ctx().names.ci} and is automatically kept up to date as you push.
If you push custom code to the preview branch, ${Link({ + text: `re-run this workflow`, + href: ctx().urls.run + })} to update the comment.
Last updated: ${dateString}` + )} + `; + return fullComment; } -function maybe_map3(val, fn) { - if (isArray3(val)) { - const mapped = []; - for (let i = 0; i < val.length; i += 1) { - mapped.push(fn(val[i])); +function CommitMessagesSection({ + targets, + pendingAiCommitMessages, + targetCommitMessages, + commitMessage +}) { + return targets.map((target) => { + const statusText = pendingAiCommitMessages?.has(target) ? `${Symbol2.HourglassFlowingSand} (generating...)` : ""; + const message = targetCommitMessages[target] ?? commitMessage; + return Dedent` + **${target}** + ${statusText}${CodeBlock(message)} + `; + }).join("\n"); +} +var DiagnosticIcon = { + fatal: Symbol2.Exclamation, + error: Symbol2.Exclamation, + warning: Symbol2.Warning, + note: Symbol2.Bulb +}; +function Results({ + orgName, + projectName, + branch, + outcomes, + baseOutcomes +}) { + const results = []; + let hasPending = false; + Object.entries(outcomes).forEach(([lang, head]) => { + const base = baseOutcomes?.[lang]; + hasPending ||= categorizeOutcome({ + outcome: head, + baseOutcome: base + }).isPending ?? false; + const result = Result({ + orgName, + projectName, + branch, + lang, + head, + base + }); + if (result) { + results.push(result); } - return mapped; - } - return fn(val); -} - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/qs/stringify.mjs -var array_prefix_generators3 = { - brackets(prefix) { - return String(prefix) + "[]"; - }, - comma: "comma", - indices(prefix, key) { - return String(prefix) + "[" + key + "]"; - }, - repeat(prefix) { - return String(prefix); + }); + if (hasPending) { + results.push( + Dedent` + ${Symbol2.HourglassFlowingSand} These are partial results; builds are still running. + ` + ); } -}; -var push_to_array3 = function(arr, value_or_array) { - Array.prototype.push.apply(arr, isArray3(value_or_array) ? value_or_array : [value_or_array]); -}; -var toISOString3; -var defaults3 = { - addQueryPrefix: false, - allowDots: false, - allowEmptyArrays: false, - arrayFormat: "indices", - charset: "utf-8", - charsetSentinel: false, - delimiter: "&", - encode: true, - encodeDotInKeys: false, - encoder: encode3, - encodeValuesOnly: false, - format: default_format3, - formatter: default_formatter3, - /** @deprecated */ - indices: false, - serializeDate(date) { - return (toISOString3 ?? (toISOString3 = Function.prototype.call.bind(Date.prototype.toISOString)))(date); - }, - skipNulls: false, - strictNullHandling: false -}; -function is_non_nullish_primitive3(v) { - return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint"; + return results.join("\n\n"); } -var sentinel3 = {}; -function inner_stringify3(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { - let obj = object; - let tmp_sc = sideChannel; - let step = 0; - let find_flag = false; - while ((tmp_sc = tmp_sc.get(sentinel3)) !== void 0 && !find_flag) { - const pos = tmp_sc.get(object); - step += 1; - if (typeof pos !== "undefined") { - if (pos === step) { - throw new RangeError("Cyclic object value"); - } else { - find_flag = true; - } - } - if (typeof tmp_sc.get(sentinel3) === "undefined") { - step = 0; +function Result({ + orgName, + projectName, + branch, + lang, + head, + base +}) { + const categorized = categorizeOutcome({ + outcome: head, + baseOutcome: base + }); + const { ResultIcon, Description } = (() => { + if (categorized.isPending) { + return { + ResultIcon: Symbol2.HourglassFlowingSand, + Description: "" + }; } - } - if (typeof filter === "function") { - obj = filter(prefix, obj); - } else if (obj instanceof Date) { - obj = serializeDate?.(obj); - } else if (generateArrayPrefix === "comma" && isArray3(obj)) { - obj = maybe_map3(obj, function(value) { - if (value instanceof Date) { - return serializeDate?.(value); - } - return value; + const { severity, conclusion, isRegression, description } = categorized; + const reason = getReason({ + description, + isRegression }); - } - if (obj === null) { - if (strictNullHandling) { - return encoder && !encodeValuesOnly ? ( - // @ts-expect-error - encoder(prefix, defaults3.encoder, charset, "key", format) - ) : prefix; - } - obj = ""; - } - if (is_non_nullish_primitive3(obj) || is_buffer3(obj)) { - if (encoder) { - const key_value = encodeValuesOnly ? prefix : encoder(prefix, defaults3.encoder, charset, "key", format); - return [ - formatter?.(key_value) + "=" + // @ts-expect-error - formatter?.(encoder(obj, defaults3.encoder, charset, "value", format)) - ]; + if (isRegression !== false && severity === "fatal") { + return { + ResultIcon: Symbol2.Exclamation, + Description: Italic(reason) + }; } - return [formatter?.(prefix) + "=" + formatter?.(String(obj))]; - } - const values = []; - if (typeof obj === "undefined") { - return values; - } - let obj_keys; - if (generateArrayPrefix === "comma" && isArray3(obj)) { - if (encodeValuesOnly && encoder) { - obj = maybe_map3(obj, encoder); + if (isRegression !== false && conclusion === "merge_conflict") { + return { + ResultIcon: Symbol2.Zap, + Description: [ + Italic(reason), + Italic( + `You don't need to resolve this conflict right now, but you will need to resolve it for your changes to be released to your users. Read more about why this happened ${Link({ + text: "here", + href: "https://www.stainless.com/docs/guides/add-custom-code" + })}.` + ) + ].join("\n") + }; } - obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; - } else if (isArray3(filter)) { - obj_keys = filter; - } else { - const keys = Object.keys(obj); - obj_keys = sort ? keys.sort(sort) : keys; - } - const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix); - const adjusted_prefix = commaRoundTrip && isArray3(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix; - if (allowEmptyArrays && isArray3(obj) && obj.length === 0) { - return adjusted_prefix + "[]"; - } - for (let j = 0; j < obj_keys.length; ++j) { - const key = obj_keys[j]; - const value = ( - // @ts-ignore - typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key] - ); - if (skipNulls && value === null) { - continue; + if (isRegression !== false && severity !== "note" && severity !== null) { + return { + ResultIcon: Symbol2.Warning, + Description: Italic(reason) + }; } - const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key; - const key_prefix = isArray3(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]"); - sideChannel.set(object, step); - const valueSideChannel = /* @__PURE__ */ new WeakMap(); - valueSideChannel.set(sentinel3, sideChannel); - push_to_array3(values, inner_stringify3( - value, - key_prefix, - generateArrayPrefix, - commaRoundTrip, - allowEmptyArrays, - strictNullHandling, - skipNulls, - encodeDotInKeys, - // @ts-ignore - generateArrayPrefix === "comma" && encodeValuesOnly && isArray3(obj) ? null : encoder, - filter, - sort, - allowDots, - serializeDate, - format, - formatter, - encodeValuesOnly, - charset, - valueSideChannel - )); - } - return values; + return { + ResultIcon: severity === "fatal" ? Symbol2.Construction : Symbol2.WhiteCheckMark, + Description: Italic(reason) + }; + })(); + return Details({ + summary: [ + ResultIcon, + Bold(`${projectName}-${lang}`), + [ + Link({ + text: "studio", + href: `https://app.stainless.com/${orgName}/${projectName}/studio?language=${lang}&branch=${encodeURIComponent(branch)}` + }), + GitHubLink(head), + base ? CompareLink(base, head) : null, + MergeConflictLink(head) + ].filter((link) => link !== null).join(` ${Symbol2.MiddleDot} `) + ].join(" "), + body: [ + Description, + StatusLine(base, head), + InstallationDetails(head, lang), + base ? DiagnosticsDetails(head, base) : null + ].filter((value) => Boolean(value)).join("\n"), + open: !categorized.isPending && categorized.isRegression !== false && categorized.severity !== "note" && categorized.severity !== null + }); +} +function StatusLine(base, head) { + return [ + StatusStep(base, head, "generate"), + StatusStep(base, head, "build"), + StatusStep(base, head, "lint"), + StatusStep(base, head, "test") + ].filter((value) => Boolean(value)).join(` ${Symbol2.RightwardsArrow} `); } -function normalize_stringify_options3(opts = defaults3) { - if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") { - throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); +function StatusStep(base, head, step) { + let baseStatus = base ? StatusSymbol(base, step) : null; + let headStatus = StatusSymbol(head, step); + if (!headStatus) { + return null; } - if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") { - throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided"); + if (baseStatus === Symbol2.HourglassFlowingSand || headStatus === Symbol2.HourglassFlowingSand) { + baseStatus = Symbol2.HourglassFlowingSand; + headStatus = Symbol2.HourglassFlowingSand; } - if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") { - throw new TypeError("Encoder has to be a function."); + const headText = CodeInline(`${step} ${headStatus}`); + const headURL = StatusURL(head, step); + const headLink = headURL ? Link({ text: headText, href: headURL }) : headText; + if (!baseStatus || baseStatus === headStatus) { + return headLink; } - const charset = opts.charset || defaults3.charset; - if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { - throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); + const baseText = CodeInline(`${step} ${baseStatus}`); + const baseURL = StatusURL(base, step); + const baseLink = baseURL ? Link({ text: baseText, href: baseURL }) : baseText; + return `${headLink} (prev: ${baseLink})`; +} +function StatusSymbol(outcome, step) { + if (!outcome.commit?.completed?.commit) { + return null; } - let format = default_format3; - if (typeof opts.format !== "undefined") { - if (!has3(formatters3, opts.format)) { - throw new TypeError("Unknown format option provided."); + if (step === "generate") { + switch (outcome.commit.completed.conclusion) { + case "fatal": + case "error": + case "cancelled": + return Symbol2.Exclamation; + case "merge_conflict": + return Symbol2.Zap; + case "upstream_merge_conflict": + case "warning": + return Symbol2.Warning; + default: + return Symbol2.WhiteCheckMark; } - format = opts.format; - } - const formatter = formatters3[format]; - let filter = defaults3.filter; - if (typeof opts.filter === "function" || isArray3(opts.filter)) { - filter = opts.filter; } - let arrayFormat; - if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators3) { - arrayFormat = opts.arrayFormat; - } else if ("indices" in opts) { - arrayFormat = opts.indices ? "indices" : "repeat"; - } else { - arrayFormat = defaults3.arrayFormat; + const stepData = outcome[step]; + if (!stepData) { + return null; } - if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") { - throw new TypeError("`commaRoundTrip` must be a boolean, or absent"); + if (stepData.status === "completed") { + return stepData.completed.conclusion === "success" ? Symbol2.WhiteCheckMark : stepData.completed.conclusion === "skipped" ? Symbol2.Skipped : Symbol2.Exclamation; } - const allowDots = typeof opts.allowDots === "undefined" ? !!opts.encodeDotInKeys === true ? true : defaults3.allowDots : !!opts.allowDots; - return { - addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults3.addQueryPrefix, - // @ts-ignore - allowDots, - allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults3.allowEmptyArrays, - arrayFormat, - charset, - charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults3.charsetSentinel, - commaRoundTrip: !!opts.commaRoundTrip, - delimiter: typeof opts.delimiter === "undefined" ? defaults3.delimiter : opts.delimiter, - encode: typeof opts.encode === "boolean" ? opts.encode : defaults3.encode, - encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults3.encodeDotInKeys, - encoder: typeof opts.encoder === "function" ? opts.encoder : defaults3.encoder, - encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults3.encodeValuesOnly, - filter, - format, - formatter, - serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults3.serializeDate, - skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults3.skipNulls, - // @ts-ignore - sort: typeof opts.sort === "function" ? opts.sort : null, - strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults3.strictNullHandling - }; + return Symbol2.HourglassFlowingSand; } -function stringify3(object, opts = {}) { - let obj = object; - const options = normalize_stringify_options3(opts); - let obj_keys; - let filter; - if (typeof options.filter === "function") { - filter = options.filter; - obj = filter("", obj); - } else if (isArray3(options.filter)) { - filter = options.filter; - obj_keys = filter; - } - const keys = []; - if (typeof obj !== "object" || obj === null) { - return ""; - } - const generateArrayPrefix = array_prefix_generators3[options.arrayFormat]; - const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip; - if (!obj_keys) { - obj_keys = Object.keys(obj); - } - if (options.sort) { - obj_keys.sort(options.sort); +function StatusURL(outcome, step) { + if (step === "generate" || !outcome[step]) { + return null; } - const sideChannel = /* @__PURE__ */ new WeakMap(); - for (let i = 0; i < obj_keys.length; ++i) { - const key = obj_keys[i]; - if (options.skipNulls && obj[key] === null) { - continue; - } - push_to_array3(keys, inner_stringify3( - obj[key], - key, - // @ts-expect-error - generateArrayPrefix, - commaRoundTrip, - options.allowEmptyArrays, - options.strictNullHandling, - options.skipNulls, - options.encodeDotInKeys, - options.encode ? options.encoder : null, - options.filter, - options.sort, - options.allowDots, - options.serializeDate, - options.format, - options.formatter, - options.encodeValuesOnly, - options.charset, - sideChannel - )); + if (outcome[step].status !== "not_started") { + return outcome[step].url; } - const joined = keys.join(options.delimiter); - let prefix = options.addQueryPrefix === true ? "?" : ""; - if (options.charsetSentinel) { - if (options.charset === "iso-8859-1") { - prefix += "utf8=%26%2310003%3B&"; - } else { - prefix += "utf8=%E2%9C%93&"; - } +} +function GitHubLink(outcome) { + if (!outcome.commit?.completed?.commit) return null; + const { + repo: { owner, name, branch } + } = outcome.commit.completed.commit; + return Link({ + text: "code", + // This is a staging repo, so it's always GitHub. + href: `https://github.com/${owner}/${name}/tree/${encodeURIComponent(branch)}` + }); +} +function CompareLink(base, head) { + if (!base.commit?.completed?.commit || !head.commit?.completed?.commit) { + return null; } - return joined.length > 0 ? prefix + joined : ""; + const { repo } = head.commit.completed.commit; + const baseBranch = base.commit.completed.commit.repo.branch; + const headBranch = head.commit.completed.commit.repo.branch; + const compareURL = `https://github.com/${repo.owner}/${repo.name}/compare/${encodeURIComponent(baseBranch)}..${encodeURIComponent(headBranch)}`; + return Link({ text: "diff", href: compareURL }); } - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/query.mjs -function stringifyQuery(query) { - return stringify3(query, { arrayFormat: "comma" }); +function MergeConflictLink(outcome) { + if (!outcome.commit?.completed?.merge_conflict_pr) return null; + const { + repo: { owner, name }, + number + } = outcome.commit.completed.merge_conflict_pr; + return Link({ + text: "conflict", + href: `https://github.com/${owner}/${name}/pull/${number}` + }); } - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/log.mjs -var levelNumbers3 = { - off: 0, - error: 200, - warn: 300, - info: 400, - debug: 500 -}; -var parseLogLevel3 = (maybeLevel, sourceName, client) => { - if (!maybeLevel) { - return void 0; +function DiagnosticsDetails(head, base) { + if (!base.diagnostics || !head.diagnostics) return null; + const newDiagnostics = getNewDiagnostics(head.diagnostics, base.diagnostics); + if (newDiagnostics.length === 0) return null; + const levelCounts = countDiagnosticLevels(newDiagnostics); + const diagnosticCounts = Object.entries(levelCounts).filter(([, count]) => count > 0).map(([level, count]) => `${count} ${level}`); + const diagnosticList = sortDiagnostics(newDiagnostics).slice(0, 10).map((d) => `${DiagnosticIcon[d.level]} ${Bold(d.code)}: ${d.message}`).filter(Boolean); + const tableRows = diagnosticList.map((diagnostic) => ` +${diagnostic} +`).join("\n"); + const tableContent = ` +${tableRows} +
`; + return Details({ + summary: `New diagnostics (${diagnosticCounts.join(", ")})`, + body: tableContent, + indent: false + }); +} +function InstallationDetails(head, lang) { + let githubGoURL = null; + let installation = null; + if (head.commit?.completed.commit) { + const { repo, sha } = head.commit.completed.commit; + githubGoURL = `github.com/${repo.owner}/${repo.name}@${sha}`; } - if (hasOwn3(levelNumbers3, maybeLevel)) { - return maybeLevel; + switch (lang) { + case "typescript": + case "node": { + if (head.install_url) { + installation = `npm install ${head.install_url}`; + } + break; + } + case "python": { + if (head.install_url) { + installation = `pip install ${head.install_url}`; + } + break; + } + case "go": { + if (githubGoURL) { + installation = `go get ${githubGoURL}`; + } + break; + } + case "java": { + if (head.install_url) { + installation = `Add the following URL as a Maven source: '${head.install_url}'`; + } + break; + } + case "cli": { + if (head.install_url) { + installation = `Download and unzip: '${head.install_url}'. On macOS, run \`xattr -d com.apple.quarantine {executable name}\`.`; + } + break; + } + default: { + return null; + } } - loggerFor3(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers3))}`); - return void 0; -}; -function noop3() { + if (!installation) return null; + return CodeBlock({ content: installation, language: "bash" }); } -function makeLogFn3(fnLevel, logger2, logLevel) { - if (!logger2 || levelNumbers3[fnLevel] > levelNumbers3[logLevel]) { - return noop3; - } else { - return logger2[fnLevel].bind(logger2); +function parseCommitMessages(body) { + if (!body) { + return {}; } -} -var noopLogger3 = { - error: noop3, - warn: noop3, - info: noop3, - debug: noop3 -}; -var cachedLoggers3 = /* @__PURE__ */ new WeakMap(); -function loggerFor3(client) { - const logger2 = client.logger; - const logLevel = client.logLevel ?? "off"; - if (!logger2) { - return noopLogger3; + const targetCommitMessages = {}; + const languageBlocks = body.matchAll( + /\*\*([a-z_]+)\*\*\s*\n```\s*\n([\s\S]*?)\n```/g + ); + for (const match of languageBlocks) { + const language = match[1]; + const message2 = match[2].trim(); + if (message2) { + targetCommitMessages[language] = makeCommitMessageConventional(message2); + } } - const cachedLogger = cachedLoggers3.get(logger2); - if (cachedLogger && cachedLogger[0] === logLevel) { - return cachedLogger[1]; + if (Object.keys(targetCommitMessages).length > 0) { + return { targetCommitMessages }; } - const levelLogger = { - error: makeLogFn3("error", logger2, logLevel), - warn: makeLogFn3("warn", logger2, logLevel), - info: makeLogFn3("info", logger2, logLevel), - debug: makeLogFn3("debug", logger2, logLevel) - }; - cachedLoggers3.set(logger2, [logLevel, levelLogger]); - return levelLogger; + const message = body?.match(/(? { - if (details.options) { - details.options = { ...details.options }; - delete details.options["headers"]; +async function retrieveComment(prNumber) { + const comments = await api().listComments(prNumber); + const existingComment = comments.find( + (comment) => comment.body?.includes(COMMENT_TITLE) + ); + if (!existingComment) { + return null; } - if (details.headers) { - details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ - name, - name.toLowerCase() === "authorization" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value - ])); + return { + id: existingComment.id, + ...parseCommitMessages(existingComment.body) + }; +} +async function upsertComment(prNumber, { + body, + skipCreate = false +}) { + logger.debug(`Upserting comment on ${ctx().names.pr} #${prNumber}`); + const comments = await api().listComments(prNumber); + const firstLine = body.trim().split("\n")[0]; + const existingComment = comments.find( + (comment) => comment.body?.includes(firstLine) + ); + if (existingComment) { + logger.debug("Updating existing comment:", existingComment.id); + await api().updateComment(prNumber, { ...existingComment, body }); + } else if (!skipCreate) { + logger.debug("Creating new comment"); + await api().createComment(prNumber, { body }); } - if ("retryOfRequestLogID" in details) { - if (details.retryOfRequestLogID) { - details.retryOf = details.retryOfRequestLogID; +} +function areCommentsEqual(a, b) { + return a.slice(0, a.indexOf(COMMENT_FOOTER_DIVIDER)) === b.slice(0, b.indexOf(COMMENT_FOOTER_DIVIDER)); +} +function commentThrottler(prNumber) { + let lastComment = null; + let lastCommentTime = null; + return async ({ body, force = false }) => { + if (force || !lastComment || !lastCommentTime || !areCommentsEqual(body, lastComment) && Date.now() - lastCommentTime.getTime() > 10 * 1e3 || Date.now() - lastCommentTime.getTime() > 30 * 1e3) { + await upsertComment(prNumber, { body }); + lastComment = body; + lastCommentTime = /* @__PURE__ */ new Date(); } - delete details.retryOfRequestLogID; - } - return details; + }; +} + +// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/context.js +var import_node_process = __toESM(require("node:process"), 1); +var import_node_util = require("node:util"); +var getContext = (raw) => ({ + start: import_node_process.default.hrtime.bigint(), + command: raw.map((part) => getCommandPart((0, import_node_util.stripVTControlCharacters)(part))).join(" "), + state: { stdout: "", stderr: "", output: "" } +}); +var getCommandPart = (part) => /[^\w./-]/.test(part) ? `'${part.replaceAll("'", "'\\''")}'` : part; + +// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/options.js +var import_node_path = __toESM(require("node:path"), 1); +var import_node_url = require("node:url"); +var import_node_process2 = __toESM(require("node:process"), 1); +var getOptions = ({ + stdin, + stdout, + stderr, + stdio = [stdin, stdout, stderr], + env: envOption, + preferLocal, + cwd: cwdOption = ".", + ...options +}) => { + const cwd = cwdOption instanceof URL ? (0, import_node_url.fileURLToPath)(cwdOption) : import_node_path.default.resolve(cwdOption); + const env = envOption ? { ...import_node_process2.default.env, ...envOption } : void 0; + const input = stdio[0]?.string; + return { + ...options, + input, + stdio: input === void 0 ? stdio : ["pipe", ...stdio.slice(1)], + env: preferLocal ? addLocalPath(env ?? import_node_process2.default.env, cwd) : env, + cwd + }; +}; +var addLocalPath = ({ Path: Path3 = "", PATH = Path3, ...env }, cwd) => { + const pathParts = PATH.split(import_node_path.default.delimiter); + const localPaths = getLocalPaths([], import_node_path.default.resolve(cwd)).map((localPath) => import_node_path.default.join(localPath, "node_modules/.bin")).filter((localPath) => !pathParts.includes(localPath)); + return { ...env, PATH: [...localPaths, PATH].filter(Boolean).join(import_node_path.default.delimiter) }; }; +var getLocalPaths = (localPaths, localPath) => localPaths.at(-1) === localPath ? localPaths : getLocalPaths([...localPaths, localPath], import_node_path.default.resolve(localPath, "..")); -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/parse.mjs -async function defaultParseResponse3(client, props) { - const { response, requestLogID, retryOfRequestLogID, startTime } = props; - const body = await (async () => { - if (response.status === 204) { - return null; - } - if (props.options.__binaryResponse) { - return response; - } - const contentType = response.headers.get("content-type"); - const mediaType = contentType?.split(";")[0]?.trim(); - const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json"); - if (isJSON) { - const contentLength = response.headers.get("content-length"); - if (contentLength === "0") { - return void 0; - } - const json = await response.json(); - return json; - } - const text = await response.text(); - return text; - })(); - loggerFor3(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails3({ - retryOfRequestLogID, - url: response.url, - status: response.status, - body, - durationMs: Date.now() - startTime - })); - return body; -} +// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/spawn.js +var import_node_child_process = require("node:child_process"); +var import_node_events2 = require("node:events"); +var import_node_process5 = __toESM(require("node:process"), 1); -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/core/api-promise.mjs -var _APIPromise_client3; -var APIPromise3 = class _APIPromise extends Promise { - constructor(client, responsePromise, parseResponse = defaultParseResponse3) { - super((resolve) => { - resolve(null); - }); - this.responsePromise = responsePromise; - this.parseResponse = parseResponse; - _APIPromise_client3.set(this, void 0); - __classPrivateFieldSet3(this, _APIPromise_client3, client, "f"); - } - _thenUnwrap(transform) { - return new _APIPromise(__classPrivateFieldGet3(this, _APIPromise_client3, "f"), this.responsePromise, async (client, props) => transform(await this.parseResponse(client, props), props)); +// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/windows.js +var import_promises = __toESM(require("node:fs/promises"), 1); +var import_node_path2 = __toESM(require("node:path"), 1); +var import_node_process3 = __toESM(require("node:process"), 1); +var applyForceShell = async (file, commandArguments, options) => await shouldForceShell(file, options) ? [escapeFile(file), commandArguments.map((argument) => escapeArgument(argument)), { ...options, shell: true }] : [file, commandArguments, options]; +var shouldForceShell = async (file, { shell, cwd, env = import_node_process3.default.env }) => import_node_process3.default.platform === "win32" && !shell && !await isExe(file, cwd, env); +var isExe = (file, cwd, { Path: Path3 = "", PATH = Path3 }) => ( + // If the *.exe or *.com file extension was not omitted. + // Windows common file systems are case-insensitive. + exeExtensions.some((extension) => file.toLowerCase().endsWith(extension)) || mIsExe(file, cwd, PATH) +); +var EXE_MEMO = {}; +var memoize = (function_) => (...arguments_) => ( + // Use returned assignment to keep code small + EXE_MEMO[arguments_.join("\0")] ??= function_(...arguments_) +); +var access = memoize(import_promises.default.access); +var mIsExe = memoize(async (file, cwd, PATH) => { + const parts = PATH.split(import_node_path2.default.delimiter).filter(Boolean).map((part) => part.replace(/^"(.*)"$/, "$1")); + try { + await Promise.any( + [cwd, ...parts].flatMap( + (part) => exeExtensions.map((extension) => access(`${import_node_path2.default.resolve(part, file)}${extension}`)) + ) + ); + } catch { + return false; } - /** - * Gets the raw `Response` instance instead of parsing the response - * data. - * - * If you want to parse the response body but still get the `Response` - * instance, you can use {@link withResponse()}. - * - * 👋 Getting the wrong TypeScript type for `Response`? - * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` - * to your `tsconfig.json`. - */ - asResponse() { - return this.responsePromise.then((p) => p.response); + return true; +}); +var exeExtensions = [".exe", ".com"]; +var escapeArgument = (argument) => escapeFile(escapeFile(`"${argument.replaceAll(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, "$1$1")}"`)); +var escapeFile = (file) => file.replaceAll(/([()\][%!^"`<>&|;, *?])/g, "^$1"); + +// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/result.js +var import_node_events = require("node:events"); +var import_node_process4 = __toESM(require("node:process"), 1); +var getResult = async (nodeChildProcess, { input }, context) => { + const instance = await nodeChildProcess; + if (input !== void 0) { + instance.stdin.end(input); } - /** - * Gets the parsed response data and the raw `Response` instance. - * - * If you just want to get the raw `Response` instance without parsing it, - * you can use {@link asResponse()}. - * - * 👋 Getting the wrong TypeScript type for `Response`? - * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` - * to your `tsconfig.json`. - */ - async withResponse() { - const [data, response] = await Promise.all([this.parse(), this.asResponse()]); - return { data, response }; + const onClose = (0, import_node_events.once)(instance, "close"); + try { + await Promise.race([ + onClose, + ...instance.stdio.filter(Boolean).map((stream) => onStreamError(stream)) + ]); + checkFailure(context, getErrorOutput(instance)); + return getOutputs(context); + } catch (error) { + await Promise.allSettled([onClose]); + throw getResultError(error, instance, context); } - parse() { - if (!this.parsedPromise) { - this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet3(this, _APIPromise_client3, "f"), data)); +}; +var onStreamError = async (stream) => { + for await (const [error] of (0, import_node_events.on)(stream, "error")) { + if (!["ERR_STREAM_PREMATURE_CLOSE", "EPIPE"].includes(error?.code)) { + throw error; } - return this.parsedPromise; - } - then(onfulfilled, onrejected) { - return this.parse().then(onfulfilled, onrejected); } - catch(onrejected) { - return this.parse().catch(onrejected); +}; +var checkFailure = ({ command }, { exitCode, signalName }) => { + if (signalName !== void 0) { + throw new SubprocessError(`Command was terminated with ${signalName}: ${command}`); } - finally(onfinally) { - return this.parse().finally(onfinally); + if (exitCode !== void 0) { + throw new SubprocessError(`Command failed with exit code ${exitCode}: ${command}`); } }; -_APIPromise_client3 = /* @__PURE__ */ new WeakMap(); +var getResultError = (error, instance, context) => Object.assign( + getErrorInstance(error, context), + getErrorOutput(instance), + getOutputs(context) +); +var getErrorInstance = (error, { command }) => error instanceof SubprocessError ? error : new SubprocessError(`Command failed: ${command}`, { cause: error }); +var SubprocessError = class extends Error { + name = "SubprocessError"; +}; +var getErrorOutput = ({ exitCode, signalCode }) => ({ + // `exitCode` can be a negative number (`errno`) when the `error` event is emitted on the `instance` + ...exitCode < 1 ? {} : { exitCode }, + ...signalCode === null ? {} : { signalName: signalCode } +}); +var getOutputs = ({ state: { stdout, stderr, output }, command, start }) => ({ + stdout: getOutput(stdout), + stderr: getOutput(stderr), + output: getOutput(output), + command, + durationMs: Number(import_node_process4.default.hrtime.bigint() - start) / 1e6 +}); +var getOutput = (output) => output.at(-1) === "\n" ? output.slice(0, output.at(-2) === "\r" ? -2 : -1) : output; -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/core/pagination.mjs -var _AbstractPage_client2; -var AbstractPage2 = class { - constructor(client, response, body, options) { - _AbstractPage_client2.set(this, void 0); - __classPrivateFieldSet3(this, _AbstractPage_client2, client, "f"); - this.options = options; - this.response = response; - this.body = body; - } - hasNextPage() { - const items = this.getPaginatedItems(); - if (!items.length) - return false; - return this.nextPageRequestOptions() != null; - } - async getNextPage() { - const nextOptions = this.nextPageRequestOptions(); - if (!nextOptions) { - throw new StainlessError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`."); +// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/spawn.js +var spawnSubprocess = async (file, commandArguments, options, context) => { + try { + if (["node", "node.exe"].includes(file.toLowerCase())) { + file = import_node_process5.default.execPath; + commandArguments = [...import_node_process5.default.execArgv.filter((flag) => !flag.startsWith("--inspect")), ...commandArguments]; } - return await __classPrivateFieldGet3(this, _AbstractPage_client2, "f").requestAPIList(this.constructor, nextOptions); + [file, commandArguments, options] = await applyForceShell(file, commandArguments, options); + [file, commandArguments, options] = concatenateShell(file, commandArguments, options); + const instance = (0, import_node_child_process.spawn)(file, commandArguments, options); + bufferOutput(instance.stdout, context, "stdout"); + bufferOutput(instance.stderr, context, "stderr"); + instance.once("error", () => { + }); + await (0, import_node_events2.once)(instance, "spawn"); + return instance; + } catch (error) { + throw getResultError(error, {}, context); } - async *iterPages() { - let page = this; - yield page; - while (page.hasNextPage()) { - page = await page.getNextPage(); - yield page; +}; +var concatenateShell = (file, commandArguments, options) => options.shell && commandArguments.length > 0 ? [[file, ...commandArguments].join(" "), [], options] : [file, commandArguments, options]; +var bufferOutput = (stream, { state }, streamName) => { + if (stream) { + stream.setEncoding("utf8"); + if (!state.isIterating) { + state.isIterating = false; + stream.on("data", (chunk) => { + state[streamName] += chunk; + state.output += chunk; + }); } } - async *[(_AbstractPage_client2 = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() { - for await (const page of this.iterPages()) { - for (const item of page.getPaginatedItems()) { - yield item; - } +}; + +// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/pipe.js +var import_promises2 = require("node:stream/promises"); +var handlePipe = async (subprocesses) => { + const [[from, to]] = await Promise.all([Promise.allSettled(subprocesses), pipeStreams(subprocesses)]); + if (to.reason) { + to.reason.pipedFrom = from.reason ?? from.value; + throw to.reason; + } + if (from.reason) { + throw from.reason; + } + return { ...to.value, pipedFrom: from.value }; +}; +var pipeStreams = async (subprocesses) => { + try { + const [{ stdout }, { stdin }] = await Promise.all(subprocesses.map(({ nodeChildProcess }) => nodeChildProcess)); + if (stdin === null) { + throw new Error('The "stdin" option must be set on the first "spawn()" call in the pipeline.'); } + if (stdout === null) { + throw new Error('The "stdout" option must be set on the last "spawn()" call in the pipeline.'); + } + (0, import_promises2.pipeline)(stdout, stdin).catch(() => { + }); + } catch (error) { + await Promise.allSettled(subprocesses.map(({ nodeChildProcess }) => closeStdin(nodeChildProcess))); + throw error; } }; -var PagePromise2 = class extends APIPromise3 { - constructor(client, request, Page2) { - super(client, request, async (client2, props) => new Page2(client2, props.response, await defaultParseResponse3(client2, props), props.options)); +var closeStdin = async (nodeChildProcess) => { + const { stdin } = await nodeChildProcess; + stdin.end(); +}; + +// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/iterable.js +var readline = __toESM(require("node:readline/promises"), 1); +var lineIterator = async function* (subprocess, { state }, streamName) { + if (state.isIterating === false) { + throw new Error(`The subprocess must be iterated right away, for example: + for await (const line of spawn(...)) { ... }`); } - /** - * Allow auto-paginating iteration on an unawaited list call, eg: - * - * for await (const item of client.items.list()) { - * console.log(item) - * } - */ - async *[Symbol.asyncIterator]() { - const page = await this; - for await (const item of page) { - yield item; + state.isIterating = true; + try { + const { [streamName]: stream } = await subprocess.nodeChildProcess; + if (!stream) { + return; } + handleErrors(subprocess); + yield* readline.createInterface({ input: stream }); + } finally { + await subprocess; } }; -var Page = class extends AbstractPage2 { - constructor(client, response, body, options) { - super(client, response, body, options); - this.data = body.data || []; - this.next_cursor = body.next_cursor || ""; - } - getPaginatedItems() { - return this.data ?? []; +var handleErrors = async (subprocess) => { + try { + await subprocess; + } catch { } - nextPageRequestOptions() { - const cursor = this.next_cursor; - if (!cursor) { - return null; - } - return { - ...this.options, - query: { - ...maybeObj2(this.options.query), - cursor +}; +var combineAsyncIterators = async function* (...iterators) { + try { + let promises = []; + while (iterators.length > 0) { + promises = iterators.map((iterator2, index2) => promises[index2] ?? getNext(iterator2)); + const [{ value, done }, index] = await Promise.race(promises.map((promise, index2) => Promise.all([promise, index2]))); + const [iterator] = iterators.splice(index, 1); + promises.splice(index, 1); + if (!done) { + iterators.push(iterator); + yield value; } - }; + } + } finally { + await Promise.all(iterators.map((iterator) => iterator.return())); } }; - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/uploads.mjs -var checkFileSupport3 = () => { - if (typeof File === "undefined") { - const { process: process7 } = globalThis; - const isOldNode = typeof process7?.versions?.node === "string" && parseInt(process7.versions.node.split(".")) < 20; - throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : "")); +var getNext = async (iterator) => { + try { + return await iterator.next(); + } catch (error) { + await iterator.throw(error); } }; -function makeFile3(fileBits, fileName, options) { - checkFileSupport3(); - return new File(fileBits, fileName ?? "unknown_file", options); -} -function getName3(value) { - return (typeof value === "object" && value !== null && ("name" in value && value.name && String(value.name) || "url" in value && value.url && String(value.url) || "filename" in value && value.filename && String(value.filename) || "path" in value && value.path && String(value.path)) || "").split(/[\\/]/).pop() || void 0; + +// node_modules/.pnpm/nano-spawn@1.0.3/node_modules/nano-spawn/source/index.js +function spawn2(file, second, third, previous) { + const [commandArguments = [], options = {}] = Array.isArray(second) ? [second, third] : [[], second]; + const context = getContext([file, ...commandArguments]); + const spawnOptions = getOptions(options); + const nodeChildProcess = spawnSubprocess(file, commandArguments, spawnOptions, context); + let subprocess = getResult(nodeChildProcess, spawnOptions, context); + Object.assign(subprocess, { nodeChildProcess }); + subprocess = previous ? handlePipe([previous, subprocess]) : subprocess; + const stdout = lineIterator(subprocess, context, "stdout"); + const stderr = lineIterator(subprocess, context, "stderr"); + return Object.assign(subprocess, { + nodeChildProcess, + stdout, + stderr, + [Symbol.asyncIterator]: () => combineAsyncIterators(stdout, stderr), + pipe: (file2, second2, third2) => spawn2(file2, second2, third2, subprocess) + }); } -var isAsyncIterable3 = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function"; -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/to-file.mjs -var isBlobLike = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function"; -var isFileLike = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value); -var isResponseLike = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function"; -async function toFile3(value, name, options) { - checkFileSupport3(); - value = await value; - if (isFileLike(value)) { - if (value instanceof File) { - return value; - } - return makeFile3([await value.arrayBuffer()], value.name); +// src/config.ts +var fs4 = __toESM(require("node:fs")); +var import_node_os = require("node:os"); +var path6 = __toESM(require("node:path")); +function getSavedFilePath(file, sha, extension) { + return path6.join( + (0, import_node_os.tmpdir)(), + "stainless-generated-config", + `${file}-${sha}${extension}` + ); +} +async function saveConfig({ + oasPath, + configPath +}) { + let hasOAS = false; + let hasConfig = false; + const savedSha = (await spawn2("git", ["rev-parse", "HEAD"])).stdout.trim(); + if (!savedSha) { + throw new Error("Unable to determine current SHA; is there a git repo?"); } - if (isResponseLike(value)) { - const blob = await value.blob(); - name || (name = new URL(value.url).pathname.split(/[\\/]/).pop()); - return makeFile3(await getBytes(blob), name, options); + logger.info("Saving generated config for", savedSha); + if (oasPath && fs4.existsSync(oasPath)) { + hasOAS = true; + const savedFilePath = getSavedFilePath( + "oas", + savedSha, + path6.extname(oasPath) + ); + fs4.mkdirSync(path6.dirname(savedFilePath), { recursive: true }); + fs4.copyFileSync(oasPath, savedFilePath); + fs4.rmSync(oasPath); + logger.info(`Saved OAS file to ${savedFilePath}`); } - const parts = await getBytes(value); - name || (name = getName3(value)); - if (!options?.type) { - const type = parts.find((part) => typeof part === "object" && "type" in part && part.type); - if (typeof type === "string") { - options = { ...options, type }; - } + if (configPath && fs4.existsSync(configPath)) { + hasConfig = true; + const savedFilePath = getSavedFilePath( + "config", + savedSha, + path6.extname(configPath) + ); + fs4.mkdirSync(path6.dirname(savedFilePath), { recursive: true }); + fs4.copyFileSync(configPath, savedFilePath); + fs4.rmSync(configPath); + logger.info(`Saved config file to ${savedFilePath}`); } - return makeFile3(parts, name, options); + return { hasOAS, hasConfig, savedSha }; } -async function getBytes(value) { - let parts = []; - if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. - value instanceof ArrayBuffer) { - parts.push(value); - } else if (isBlobLike(value)) { - parts.push(value instanceof Blob ? value : await value.arrayBuffer()); - } else if (isAsyncIterable3(value)) { - for await (const chunk of value) { - parts.push(...await getBytes(chunk)); +async function readConfig({ + oasPath, + configPath, + sha, + required = false +}) { + sha ??= (await spawn2("git", ["rev-parse", "HEAD"])).stdout; + if (!sha) { + throw new Error("Unable to determine current SHA; is there a git repo?"); + } + logger.info("Reading config at SHA", sha); + const results = {}; + const addToResults = async (file, filePath, via) => { + if (results[file]) { + return; } - } else { - const constructor = value?.constructor?.name; - throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError(value)}`); + if (!filePath || !fs4.existsSync(filePath)) { + logger.debug(`Skipping missing ${file} at ${filePath}`); + return; + } + results[file] = fs4.readFileSync(filePath, "utf-8"); + results[`${file}Hash`] = (await spawn2("md5sum", [filePath])).stdout.split( + " " + )[0]; + logger.info(`Using ${file} via ${via}`, { hash: results[`${file}Hash`] }); + }; + try { + await spawn2("git", ["fetch", "--depth=1", "origin", sha]).catch(() => null); + await spawn2("git", ["checkout", sha, "--", "."]); + } catch { + logger.debug("Could not checkout", sha); } - return parts; -} -function propsForError(value) { - if (typeof value !== "object" || value === null) - return ""; - const props = Object.getOwnPropertyNames(value); - return `; props: [${props.map((p) => `"${p}"`).join(", ")}]`; -} - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/core/resource.mjs -var APIResource3 = class { - constructor(client) { - this._client = client; + await addToResults("oas", oasPath, `git ${sha}`); + await addToResults("config", configPath, `git ${sha}`); + try { + await addToResults( + "oas", + getSavedFilePath("oas", sha, path6.extname(oasPath ?? "")), + `saved ${sha}` + ); + await addToResults( + "config", + getSavedFilePath("config", sha, path6.extname(configPath ?? "")), + `saved ${sha}` + ); + } catch (e) { + logger.info(`Could not get config from saved file path: ${e}`); + logger.debug("Could not get config from saved file path"); } -}; - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/path.mjs -function encodeURIPath3(str) { - return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); -} -var EMPTY3 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); -var createPathTagFunction3 = (pathEncoder = encodeURIPath3) => function path7(statics, ...params) { - if (statics.length === 1) - return statics[0]; - let postPath = false; - const invalidSegments = []; - const path8 = statics.reduce((previousValue, currentValue, index) => { - if (/[?#]/.test(currentValue)) { - postPath = true; + if (required) { + if (oasPath && !results.oas) { + throw new Error(`Missing OpenAPI spec at ${oasPath} for ${sha}`); } - const value = params[index]; - let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value); - if (index !== params.length && (value == null || typeof value === "object" && // handle values from other realms - value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY3) ?? EMPTY3)?.toString)) { - encoded = value + ""; - invalidSegments.push({ - start: previousValue.length + currentValue.length, - length: encoded.length, - error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter` - }); + if (configPath && !results.config) { + throw new Error(`Missing config at ${configPath} for ${sha}`); } - return previousValue + currentValue + (index === params.length ? "" : encoded); - }, ""); - const pathOnly = path8.split(/[?#]/, 1)[0]; - const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; - let match; - while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) { - invalidSegments.push({ - start: match.index, - length: match[0].length, - error: `Value "${match[0]}" can't be safely passed as a path parameter` - }); - } - invalidSegments.sort((a, b) => a.start - b.start); - if (invalidSegments.length > 0) { - let lastEnd = 0; - const underline = invalidSegments.reduce((acc, segment) => { - const spaces = " ".repeat(segment.start - lastEnd); - const arrows = "^".repeat(segment.length); - lastEnd = segment.start + segment.length; - return acc + spaces + arrows; - }, ""); - throw new StainlessError(`Path parameters result in path with invalid segments: -${invalidSegments.map((e) => e.error).join("\n")} -${path8} -${underline}`); } - return path8; -}; -var path6 = /* @__PURE__ */ createPathTagFunction3(encodeURIPath3); - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/builds/diagnostics.mjs -var Diagnostics = class extends APIResource3 { - /** - * Get the list of diagnostics for a given build. - * - * If no language targets are specified, diagnostics for all languages are - * returned. - */ - list(buildID, query = {}, options) { - return this._client.getAPIList(path6`/v0/builds/${buildID}/diagnostics`, Page, { - query, - ...options - }); + return results; +} +async function getMergeBase({ + baseSha, + headSha +}) { + try { + await spawn2("git", ["fetch", "--depth=1", "origin", baseSha, headSha]); + } catch { + throw new Error( + `Cannot fetch ${baseSha} or ${headSha} from origin. Is there a git repo?` + ); } -}; - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/builds/target-outputs.mjs -var TargetOutputs = class extends APIResource3 { - /** - * Retrieve a method to download an output for a given build target. - * - * If the requested type of output is `source`, and the requested output method is - * `url`, a download link to a tarball of the source files is returned. If the - * requested output method is `git`, a Git remote, ref, and access token (if - * necessary) is returned. - * - * Otherwise, the possible types of outputs are specific to the requested target, - * and the output method _must_ be `url`. See the documentation for `type` for more - * information. - */ - retrieve(query, options) { - return this._client.get("/v0/build_target_outputs", { query, ...options }); + let mergeBaseSha; + try { + const output = await spawn2("git", ["merge-base", headSha, baseSha]); + mergeBaseSha = output.stdout.trim(); + } catch { } -}; - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/builds/builds.mjs -var Builds2 = class extends APIResource3 { - constructor() { - super(...arguments); - this.diagnostics = new Diagnostics(this._client); - this.targetOutputs = new TargetOutputs(this._client); + const deepenAmounts = [50, 100, 200, 400]; + for (const deepenAmount of deepenAmounts) { + if (mergeBaseSha) break; + try { + await spawn2("git", [ + "fetch", + "--quiet", + `--deepen=${deepenAmount}`, + "origin" + ]); + } catch { + } + try { + const output = await spawn2("git", ["merge-base", headSha, baseSha]); + mergeBaseSha = output.stdout.trim(); + if (mergeBaseSha) break; + } catch { + } } - /** - * Create a build, on top of a project branch, against a given input revision. - * - * The project branch will be modified so that its latest set of config files - * points to the one specified by the input revision. - */ - create(params, options) { - const { project = this._client.project, ...body } = params; - return this._client.post("/v0/builds", { body: { project, ...body }, ...options }); + if (!mergeBaseSha) { + console.log("Deepening did not find merge base, trying unshallow fetch..."); + try { + await spawn2("git", ["fetch", "--quiet", "--unshallow", "origin"]); + } catch { + } + try { + const output = await spawn2("git", ["merge-base", headSha, baseSha]); + mergeBaseSha = output.stdout.trim(); + } catch { + } } - /** - * Retrieve a build by its ID. - */ - retrieve(buildID, options) { - return this._client.get(path6`/v0/builds/${buildID}`, options); + if (!mergeBaseSha) { + throw new Error( + `Could not determine merge base SHA between ${headSha} and ${baseSha}. This may happen if the branches have completely diverged or if there is insufficient git history. Try using 'fetch-depth: 0' in your checkout step.` + ); } - /** - * List user-triggered builds for a given project. - * - * An optional revision can be specified to filter by config commit SHA, or hashes - * of file contents. - */ - list(params = {}, options) { - const { project = this._client.project, ...query } = params ?? {}; - return this._client.getAPIList("/v0/builds", Page, { query: { project, ...query }, ...options }); + logger.debug(`Merge base: ${mergeBaseSha}`); + return { mergeBaseSha }; +} +async function getNonMainBaseRef({ + baseRef, + defaultBranch +}) { + let nonMainBaseRef; + if (baseRef !== defaultBranch) { + nonMainBaseRef = `preview/${baseRef}`; + logger.debug(`Non-main base ref: ${nonMainBaseRef}`); } - /** - * Create two builds whose outputs can be directly compared with each other. - * - * Created builds _modify_ their project branches so that their latest sets of - * config files point to the ones specified by the input revision. - * - * This endpoint is useful because a build has more inputs than the set of config - * files it uses, so comparing two builds directly may return spurious differences. - * Builds made via this endpoint are guaranteed to have differences arising from - * the set of config files, and any custom code. - */ - compare(params, options) { - const { project = this._client.project, ...body } = params; - return this._client.post("/v0/builds/compare", { body: { project, ...body }, ...options }); + return { nonMainBaseRef }; +} +async function isConfigChanged({ + before, + after +}) { + let changed = false; + if (before.oasHash !== after.oasHash) { + logger.debug("OAS file changed"); + changed = true; } -}; -Builds2.Diagnostics = Diagnostics; -Builds2.TargetOutputs = TargetOutputs; + if (before.configHash !== after.configHash) { + logger.debug("Config file changed"); + changed = true; + } + return changed; +} -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/orgs.mjs -var Orgs3 = class extends APIResource3 { - /** - * Retrieve an organization by name. - */ - retrieve(org, options) { - return this._client.get(path6`/v0/orgs/${org}`, options); +// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/diff/base.js +var Diff = class { + diff(oldStr, newStr, options = {}) { + let callback; + if (typeof options === "function") { + callback = options; + options = {}; + } else if ("callback" in options) { + callback = options.callback; + } + const oldString = this.castInput(oldStr, options); + const newString = this.castInput(newStr, options); + const oldTokens = this.removeEmpty(this.tokenize(oldString, options)); + const newTokens = this.removeEmpty(this.tokenize(newString, options)); + return this.diffWithOptionsObj(oldTokens, newTokens, options, callback); } - /** - * List organizations accessible to the current authentication method. - */ - list(options) { - return this._client.get("/v0/orgs", options); + diffWithOptionsObj(oldTokens, newTokens, options, callback) { + var _a2; + const done = (value) => { + value = this.postProcess(value, options); + if (callback) { + setTimeout(function() { + callback(value); + }, 0); + return void 0; + } else { + return value; + } + }; + const newLen = newTokens.length, oldLen = oldTokens.length; + let editLength = 1; + let maxEditLength = newLen + oldLen; + if (options.maxEditLength != null) { + maxEditLength = Math.min(maxEditLength, options.maxEditLength); + } + const maxExecutionTime = (_a2 = options.timeout) !== null && _a2 !== void 0 ? _a2 : Infinity; + const abortAfterTimestamp = Date.now() + maxExecutionTime; + const bestPath = [{ oldPos: -1, lastComponent: void 0 }]; + let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options); + if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) { + return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens)); + } + let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity; + const execEditLength = () => { + for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) { + let basePath; + const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1]; + if (removePath) { + bestPath[diagonalPath - 1] = void 0; + } + let canAdd = false; + if (addPath) { + const addPathNewPos = addPath.oldPos - diagonalPath; + canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen; + } + const canRemove = removePath && removePath.oldPos + 1 < oldLen; + if (!canAdd && !canRemove) { + bestPath[diagonalPath] = void 0; + continue; + } + if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) { + basePath = this.addToPath(addPath, true, false, 0, options); + } else { + basePath = this.addToPath(removePath, false, true, 1, options); + } + newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options); + if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) { + return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true; + } else { + bestPath[diagonalPath] = basePath; + if (basePath.oldPos + 1 >= oldLen) { + maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1); + } + if (newPos + 1 >= newLen) { + minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1); + } + } + } + editLength++; + }; + if (callback) { + (function exec() { + setTimeout(function() { + if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) { + return callback(void 0); + } + if (!execEditLength()) { + exec(); + } + }, 0); + })(); + } else { + while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) { + const ret = execEditLength(); + if (ret) { + return ret; + } + } + } } -}; - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/projects/branches.mjs -var Branches3 = class extends APIResource3 { - /** - * Create a new branch for a project. - * - * The branch inherits the config files from the revision pointed to by the - * `branch_from` parameter. In addition, if the revision is a branch name, the - * branch will also inherit custom code changes from that branch. - */ - create(params, options) { - const { project = this._client.project, ...body } = params; - return this._client.post(path6`/v0/projects/${project}/branches`, { body, ...options }); + addToPath(path7, added, removed, oldPosInc, options) { + const last = path7.lastComponent; + if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) { + return { + oldPos: path7.oldPos + oldPosInc, + lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent } + }; + } else { + return { + oldPos: path7.oldPos + oldPosInc, + lastComponent: { count: 1, added, removed, previousComponent: last } + }; + } } - /** - * Retrieve a project branch by name. - */ - retrieve(branch, params = {}, options) { - const { project = this._client.project } = params ?? {}; - return this._client.get(path6`/v0/projects/${project}/branches/${branch}`, options); + extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) { + const newLen = newTokens.length, oldLen = oldTokens.length; + let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0; + while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) { + newPos++; + oldPos++; + commonCount++; + if (options.oneChangePerToken) { + basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false }; + } + } + if (commonCount && !options.oneChangePerToken) { + basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false }; + } + basePath.oldPos = oldPos; + return newPos; } - /** - * Retrieve a project branch by name. - */ - list(params = {}, options) { - const { project = this._client.project, ...query } = params ?? {}; - return this._client.getAPIList(path6`/v0/projects/${project}/branches`, Page, { - query, - ...options - }); + equals(left, right, options) { + if (options.comparator) { + return options.comparator(left, right); + } else { + return left === right || !!options.ignoreCase && left.toLowerCase() === right.toLowerCase(); + } + } + removeEmpty(array) { + const ret = []; + for (let i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]); + } + } + return ret; } - /** - * Delete a project branch by name. - */ - delete(branch, params = {}, options) { - const { project = this._client.project } = params ?? {}; - return this._client.delete(path6`/v0/projects/${project}/branches/${branch}`, options); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + castInput(value, options) { + return value; } - /** - * Rebase a project branch. - * - * The branch is rebased onto the `base` branch or commit SHA, inheriting any - * config and custom code changes. - */ - rebase(branch, params = {}, options) { - const { project = this._client.project, base } = params ?? {}; - return this._client.put(path6`/v0/projects/${project}/branches/${branch}/rebase`, { - query: { base }, - ...options - }); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + tokenize(value, options) { + return Array.from(value); } - /** - * Reset a project branch. - * - * If `branch` === `main`, the branch is reset to `target_config_sha`. Otherwise, - * the branch is reset to `main`. - */ - reset(branch, params = {}, options) { - const { project = this._client.project, target_config_sha } = params ?? {}; - return this._client.put(path6`/v0/projects/${project}/branches/${branch}/reset`, { - query: { target_config_sha }, - ...options - }); + join(chars) { + return chars.join(""); } -}; - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/projects/configs.mjs -var Configs = class extends APIResource3 { - /** - * Retrieve the configuration files for a given project. - */ - retrieve(params = {}, options) { - const { project = this._client.project, ...query } = params ?? {}; - return this._client.get(path6`/v0/projects/${project}/configs`, { query, ...options }); + postProcess(changeObjects, options) { + return changeObjects; } - /** - * Generate suggestions for changes to config files based on an OpenAPI spec. - */ - guess(params, options) { - const { project = this._client.project, ...body } = params; - return this._client.post(path6`/v0/projects/${project}/configs/guess`, { body, ...options }); + get useLongestToken() { + return false; + } + buildValues(lastComponent, newTokens, oldTokens) { + const components = []; + let nextComponent; + while (lastComponent) { + components.push(lastComponent); + nextComponent = lastComponent.previousComponent; + delete lastComponent.previousComponent; + lastComponent = nextComponent; + } + components.reverse(); + const componentLen = components.length; + let componentPos = 0, newPos = 0, oldPos = 0; + for (; componentPos < componentLen; componentPos++) { + const component = components[componentPos]; + if (!component.removed) { + if (!component.added && this.useLongestToken) { + let value = newTokens.slice(newPos, newPos + component.count); + value = value.map(function(value2, i) { + const oldValue = oldTokens[oldPos + i]; + return oldValue.length > value2.length ? oldValue : value2; + }); + component.value = this.join(value); + } else { + component.value = this.join(newTokens.slice(newPos, newPos + component.count)); + } + newPos += component.count; + if (!component.added) { + oldPos += component.count; + } + } else { + component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count)); + oldPos += component.count; + } + } + return components; } }; -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/projects/projects.mjs -var Projects5 = class extends APIResource3 { +// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/util/string.js +function hasOnlyWinLineEndings(string) { + return string.includes("\r\n") && !string.startsWith("\n") && !string.match(/[^\r]\n/); +} +function hasOnlyUnixLineEndings(string) { + return !string.includes("\r\n") && string.includes("\n"); +} + +// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/diff/line.js +var LineDiff = class extends Diff { constructor() { super(...arguments); - this.branches = new Branches3(this._client); - this.configs = new Configs(this._client); - } - /** - * Create a new project. - */ - create(body, options) { - return this._client.post("/v0/projects", { body, ...options }); + this.tokenize = tokenize; } - /** - * Retrieve a project by name. - */ - retrieve(params = {}, options) { - const { project = this._client.project } = params ?? {}; - return this._client.get(path6`/v0/projects/${project}`, options); + equals(left, right, options) { + if (options.ignoreWhitespace) { + if (!options.newlineIsToken || !left.includes("\n")) { + left = left.trim(); + } + if (!options.newlineIsToken || !right.includes("\n")) { + right = right.trim(); + } + } else if (options.ignoreNewlineAtEof && !options.newlineIsToken) { + if (left.endsWith("\n")) { + left = left.slice(0, -1); + } + if (right.endsWith("\n")) { + right = right.slice(0, -1); + } + } + return super.equals(left, right, options); } - /** - * Update a project's properties. - */ - update(params = {}, options) { - const { project = this._client.project, ...body } = params ?? {}; - return this._client.patch(path6`/v0/projects/${project}`, { body, ...options }); +}; +var lineDiff = new LineDiff(); +function diffLines(oldStr, newStr, options) { + return lineDiff.diff(oldStr, newStr, options); +} +function tokenize(value, options) { + if (options.stripTrailingCr) { + value = value.replace(/\r\n/g, "\n"); } - /** - * List projects in an organization, from oldest to newest. - */ - list(query = {}, options) { - return this._client.getAPIList("/v0/projects", Page, { query, ...options }); + const retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/); + if (!linesAndNewlines[linesAndNewlines.length - 1]) { + linesAndNewlines.pop(); } - /** - * Generates an AI commit message by comparing two git refs in the SDK repository. - */ - generateCommitMessage(params, options) { - const { project = this._client.project, target, ...body } = params; - return this._client.post(path6`/v0/projects/${project}/generate_commit_message`, { - query: { target }, - body, - ...options - }); + for (let i = 0; i < linesAndNewlines.length; i++) { + const line = linesAndNewlines[i]; + if (i % 2 && !options.newlineIsToken) { + retLines[retLines.length - 1] += line; + } else { + retLines.push(line); + } } -}; -Projects5.Branches = Branches3; -Projects5.Configs = Configs; + return retLines; +} -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/resources/user.mjs -var User = class extends APIResource3 { - /** - * Retrieve the currently authenticated user's information. - */ - retrieve(options) { - return this._client.get("/v0/user", options); +// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/line-endings.js +function unixToWin(patch) { + if (Array.isArray(patch)) { + return patch.map((p) => unixToWin(p)); } -}; - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/headers.mjs -var brand_privateNullableHeaders3 = /* @__PURE__ */ Symbol("brand.privateNullableHeaders"); -function* iterateHeaders3(headers) { - if (!headers) - return; - if (brand_privateNullableHeaders3 in headers) { - const { values, nulls } = headers; - yield* values.entries(); - for (const name of nulls) { - yield [name, null]; - } - return; + return Object.assign(Object.assign({}, patch), { hunks: patch.hunks.map((hunk) => Object.assign(Object.assign({}, hunk), { lines: hunk.lines.map((line, i) => { + var _a2; + return line.startsWith("\\") || line.endsWith("\r") || ((_a2 = hunk.lines[i + 1]) === null || _a2 === void 0 ? void 0 : _a2.startsWith("\\")) ? line : line + "\r"; + }) })) }); +} +function winToUnix(patch) { + if (Array.isArray(patch)) { + return patch.map((p) => winToUnix(p)); } - let shouldClear = false; - let iter; - if (headers instanceof Headers) { - iter = headers.entries(); - } else if (isReadonlyArray3(headers)) { - iter = headers; - } else { - shouldClear = true; - iter = Object.entries(headers ?? {}); + return Object.assign(Object.assign({}, patch), { hunks: patch.hunks.map((hunk) => Object.assign(Object.assign({}, hunk), { lines: hunk.lines.map((line) => line.endsWith("\r") ? line.substring(0, line.length - 1) : line) })) }); +} +function isUnix(patch) { + if (!Array.isArray(patch)) { + patch = [patch]; } - for (let row of iter) { - const name = row[0]; - if (typeof name !== "string") - throw new TypeError("expected header name to be a string"); - const values = isReadonlyArray3(row[1]) ? row[1] : [row[1]]; - let didClear = false; - for (const value of values) { - if (value === void 0) - continue; - if (shouldClear && !didClear) { - didClear = true; - yield [name, null]; + return !patch.some((index) => index.hunks.some((hunk) => hunk.lines.some((line) => !line.startsWith("\\") && line.endsWith("\r")))); +} +function isWin(patch) { + if (!Array.isArray(patch)) { + patch = [patch]; + } + return patch.some((index) => index.hunks.some((hunk) => hunk.lines.some((line) => line.endsWith("\r")))) && patch.every((index) => index.hunks.every((hunk) => hunk.lines.every((line, i) => { + var _a2; + return line.startsWith("\\") || line.endsWith("\r") || ((_a2 = hunk.lines[i + 1]) === null || _a2 === void 0 ? void 0 : _a2.startsWith("\\")); + }))); +} + +// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/parse.js +function parsePatch(uniDiff) { + const diffstr = uniDiff.split(/\n/), list = []; + let i = 0; + function parseIndex() { + const index = {}; + list.push(index); + while (i < diffstr.length) { + const line = diffstr[i]; + if (/^(---|\+\+\+|@@)\s/.test(line)) { + break; + } + const headerMatch = /^(?:Index:|diff(?: -r \w+)+)\s+/.exec(line); + if (headerMatch) { + index.index = line.substring(headerMatch[0].length).trim(); + } + i++; + } + parseFileHeader(index); + parseFileHeader(index); + index.hunks = []; + while (i < diffstr.length) { + const line = diffstr[i]; + if (/^(Index:\s|diff\s|---\s|\+\+\+\s|===================================================================)/.test(line)) { + break; + } else if (/^@@/.test(line)) { + index.hunks.push(parseHunk()); + } else if (line) { + throw new Error("Unknown line " + (i + 1) + " " + JSON.stringify(line)); + } else { + i++; } - yield [name, value]; } } -} -var buildHeaders3 = (newHeaders) => { - const targetHeaders = new Headers(); - const nullHeaders = /* @__PURE__ */ new Set(); - for (const headers of newHeaders) { - const seenHeaders = /* @__PURE__ */ new Set(); - for (const [name, value] of iterateHeaders3(headers)) { - const lowerName = name.toLowerCase(); - if (!seenHeaders.has(lowerName)) { - targetHeaders.delete(name); - seenHeaders.add(lowerName); + function parseFileHeader(index) { + const fileHeaderMatch = /^(---|\+\+\+)\s+/.exec(diffstr[i]); + if (fileHeaderMatch) { + const prefix = fileHeaderMatch[1], data = diffstr[i].substring(3).trim().split(" ", 2), header = (data[1] || "").trim(); + let fileName = data[0].replace(/\\\\/g, "\\"); + if (fileName.startsWith('"') && fileName.endsWith('"')) { + fileName = fileName.substr(1, fileName.length - 2); } - if (value === null) { - targetHeaders.delete(name); - nullHeaders.add(lowerName); + if (prefix === "---") { + index.oldFileName = fileName; + index.oldHeader = header; } else { - targetHeaders.append(name, value); - nullHeaders.delete(lowerName); + index.newFileName = fileName; + index.newHeader = header; } + i++; } } - return { [brand_privateNullableHeaders3]: true, values: targetHeaders, nulls: nullHeaders }; -}; - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/internal/utils/env.mjs -var readEnv3 = (env) => { - if (typeof globalThis.process !== "undefined") { - return globalThis.process.env?.[env]?.trim() ?? void 0; + function parseHunk() { + var _a2; + const chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); + const hunk = { + oldStart: +chunkHeader[1], + oldLines: typeof chunkHeader[2] === "undefined" ? 1 : +chunkHeader[2], + newStart: +chunkHeader[3], + newLines: typeof chunkHeader[4] === "undefined" ? 1 : +chunkHeader[4], + lines: [] + }; + if (hunk.oldLines === 0) { + hunk.oldStart += 1; + } + if (hunk.newLines === 0) { + hunk.newStart += 1; + } + let addCount = 0, removeCount = 0; + for (; i < diffstr.length && (removeCount < hunk.oldLines || addCount < hunk.newLines || ((_a2 = diffstr[i]) === null || _a2 === void 0 ? void 0 : _a2.startsWith("\\"))); i++) { + const operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? " " : diffstr[i][0]; + if (operation === "+" || operation === "-" || operation === " " || operation === "\\") { + hunk.lines.push(diffstr[i]); + if (operation === "+") { + addCount++; + } else if (operation === "-") { + removeCount++; + } else if (operation === " ") { + addCount++; + removeCount++; + } + } else { + throw new Error(`Hunk at line ${chunkHeaderIndex + 1} contained invalid line ${diffstr[i]}`); + } + } + if (!addCount && hunk.newLines === 1) { + hunk.newLines = 0; + } + if (!removeCount && hunk.oldLines === 1) { + hunk.oldLines = 0; + } + if (addCount !== hunk.newLines) { + throw new Error("Added line count did not match for hunk at line " + (chunkHeaderIndex + 1)); + } + if (removeCount !== hunk.oldLines) { + throw new Error("Removed line count did not match for hunk at line " + (chunkHeaderIndex + 1)); + } + return hunk; } - if (typeof globalThis.Deno !== "undefined") { - return globalThis.Deno.env?.get?.(env)?.trim(); + while (i < diffstr.length) { + parseIndex(); } - return void 0; -}; + return list; +} -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/lib/unwrap.mjs -async function unwrapFile(value) { - if (value === null) { - return null; +// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/util/distance-iterator.js +function distance_iterator_default(start, minLine, maxLine) { + let wantForward = true, backwardExhausted = false, forwardExhausted = false, localOffset = 1; + return function iterator() { + if (wantForward && !forwardExhausted) { + if (backwardExhausted) { + localOffset++; + } else { + wantForward = false; + } + if (start + localOffset <= maxLine) { + return start + localOffset; + } + forwardExhausted = true; + } + if (!backwardExhausted) { + if (!forwardExhausted) { + wantForward = true; + } + if (minLine <= start - localOffset) { + return start - localOffset++; + } + backwardExhausted = true; + return iterator(); + } + return void 0; + }; +} + +// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/apply.js +function applyPatch(source, patch, options = {}) { + let patches; + if (typeof patch === "string") { + patches = parsePatch(patch); + } else if (Array.isArray(patch)) { + patches = patch; + } else { + patches = [patch]; } - if (value.type === "content") { - return value.content; + if (patches.length > 1) { + throw new Error("applyPatch only works with a single input."); } - const response = await fetch(value.url); - return response.text(); + return applyStructuredPatch(source, patches[0], options); } - -// node_modules/.pnpm/@stainless-api+sdk@0.5.0/node_modules/@stainless-api/sdk/client.mjs -var _Stainless_instances; -var _a; -var _Stainless_encoder; -var _Stainless_baseURLOverridden; -var environments = { - production: "https://api.stainless.com", - staging: "https://staging.stainless.com" -}; -var Stainless = class { - /** - * API Client for interfacing with the Stainless API. - * - * @param {string | null | undefined} [opts.apiKey=process.env['STAINLESS_API_KEY'] ?? null] - * @param {string | null | undefined} [opts.project] - * @param {Environment} [opts.environment=production] - Specifies the environment URL to use for the API. - * @param {string} [opts.baseURL=process.env['STAINLESS_BASE_URL'] ?? https://api.stainless.com] - Override the default base URL for the API. - * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. - * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. - * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. - * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. - * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. - * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. - */ - constructor({ baseURL = readEnv3("STAINLESS_BASE_URL"), apiKey = readEnv3("STAINLESS_API_KEY") ?? null, project = null, ...opts } = {}) { - _Stainless_instances.add(this); - _Stainless_encoder.set(this, void 0); - this.projects = new Projects5(this); - this.builds = new Builds2(this); - this.orgs = new Orgs3(this); - this.user = new User(this); - const options = { - apiKey, - project, - ...opts, - baseURL, - environment: opts.environment ?? "production" - }; - if (baseURL && opts.environment) { - throw new StainlessError("Ambiguous URL; The `baseURL` option (or STAINLESS_BASE_URL env var) and the `environment` option are given. If you want to use the environment you must pass baseURL: null"); +function applyStructuredPatch(source, patch, options = {}) { + if (options.autoConvertLineEndings || options.autoConvertLineEndings == null) { + if (hasOnlyWinLineEndings(source) && isUnix(patch)) { + patch = unixToWin(patch); + } else if (hasOnlyUnixLineEndings(source) && isWin(patch)) { + patch = winToUnix(patch); } - this.baseURL = options.baseURL || environments[options.environment || "production"]; - this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT; - this.logger = options.logger ?? console; - const defaultLogLevel = "warn"; - this.logLevel = defaultLogLevel; - this.logLevel = parseLogLevel3(options.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel3(readEnv3("STAINLESS_LOG"), "process.env['STAINLESS_LOG']", this) ?? defaultLogLevel; - this.fetchOptions = options.fetchOptions; - this.maxRetries = options.maxRetries ?? 2; - this.fetch = options.fetch ?? getDefaultFetch3(); - __classPrivateFieldSet3(this, _Stainless_encoder, FallbackEncoder3, "f"); - this._options = options; - this.apiKey = apiKey; - this.project = project; } - /** - * Create a new client instance re-using the same options given to the current client with optional overriding. - */ - withOptions(options) { - const client = new this.constructor({ - ...this._options, - environment: options.environment ? options.environment : void 0, - baseURL: options.environment ? void 0 : this.baseURL, - maxRetries: this.maxRetries, - timeout: this.timeout, - logger: this.logger, - logLevel: this.logLevel, - fetch: this.fetch, - fetchOptions: this.fetchOptions, - apiKey: this.apiKey, - project: this.project, - ...options - }); - return client; + const lines = source.split("\n"), hunks = patch.hunks, compareLine = options.compareLine || ((lineNumber, line, operation, patchContent) => line === patchContent), fuzzFactor = options.fuzzFactor || 0; + let minLine = 0; + if (fuzzFactor < 0 || !Number.isInteger(fuzzFactor)) { + throw new Error("fuzzFactor must be a non-negative integer"); } - defaultQuery() { - return this._options.defaultQuery; + if (!hunks.length) { + return source; } - validateHeaders({ values, nulls }) { - if (this.apiKey && values.get("authorization")) { - return; + let prevLine = "", removeEOFNL = false, addEOFNL = false; + for (let i = 0; i < hunks[hunks.length - 1].lines.length; i++) { + const line = hunks[hunks.length - 1].lines[i]; + if (line[0] == "\\") { + if (prevLine[0] == "+") { + removeEOFNL = true; + } else if (prevLine[0] == "-") { + addEOFNL = true; + } + } + prevLine = line; + } + if (removeEOFNL) { + if (addEOFNL) { + if (!fuzzFactor && lines[lines.length - 1] == "") { + return false; + } + } else if (lines[lines.length - 1] == "") { + lines.pop(); + } else if (!fuzzFactor) { + return false; } - if (nulls.has("authorization")) { - return; + } else if (addEOFNL) { + if (lines[lines.length - 1] != "") { + lines.push(""); + } else if (!fuzzFactor) { + return false; } - throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "Authorization" headers to be explicitly omitted'); } - async authHeaders(opts) { - if (this.apiKey == null) { - return void 0; + function applyHunk(hunkLines, toPos, maxErrors, hunkLinesI = 0, lastContextLineMatched = true, patchedLines = [], patchedLinesLength = 0) { + let nConsecutiveOldContextLines = 0; + let nextContextLineMustMatch = false; + for (; hunkLinesI < hunkLines.length; hunkLinesI++) { + const hunkLine = hunkLines[hunkLinesI], operation = hunkLine.length > 0 ? hunkLine[0] : " ", content = hunkLine.length > 0 ? hunkLine.substr(1) : hunkLine; + if (operation === "-") { + if (compareLine(toPos + 1, lines[toPos], operation, content)) { + toPos++; + nConsecutiveOldContextLines = 0; + } else { + if (!maxErrors || lines[toPos] == null) { + return null; + } + patchedLines[patchedLinesLength] = lines[toPos]; + return applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1); + } + } + if (operation === "+") { + if (!lastContextLineMatched) { + return null; + } + patchedLines[patchedLinesLength] = content; + patchedLinesLength++; + nConsecutiveOldContextLines = 0; + nextContextLineMustMatch = true; + } + if (operation === " ") { + nConsecutiveOldContextLines++; + patchedLines[patchedLinesLength] = lines[toPos]; + if (compareLine(toPos + 1, lines[toPos], operation, content)) { + patchedLinesLength++; + lastContextLineMatched = true; + nextContextLineMustMatch = false; + toPos++; + } else { + if (nextContextLineMustMatch || !maxErrors) { + return null; + } + return lines[toPos] && (applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI + 1, false, patchedLines, patchedLinesLength + 1) || applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1)) || applyHunk(hunkLines, toPos, maxErrors - 1, hunkLinesI + 1, false, patchedLines, patchedLinesLength); + } + } } - return buildHeaders3([{ Authorization: `Bearer ${this.apiKey}` }]); - } - stringifyQuery(query) { - return stringifyQuery(query); - } - getUserAgent() { - return `${this.constructor.name}/JS ${VERSION3}`; - } - defaultIdempotencyKey() { - return `stainless-node-retry-${uuid43()}`; - } - makeStatusError(status, error, message, headers) { - return APIError3.generate(status, error, message, headers); + patchedLinesLength -= nConsecutiveOldContextLines; + toPos -= nConsecutiveOldContextLines; + patchedLines.length = patchedLinesLength; + return { + patchedLines, + oldLineLastI: toPos - 1 + }; } - buildURL(path7, query, defaultBaseURL) { - const baseURL = !__classPrivateFieldGet3(this, _Stainless_instances, "m", _Stainless_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL; - const url = isAbsoluteURL3(path7) ? new URL(path7) : new URL(baseURL + (baseURL.endsWith("/") && path7.startsWith("/") ? path7.slice(1) : path7)); - const defaultQuery = this.defaultQuery(); - if (!isEmptyObj3(defaultQuery)) { - query = { ...defaultQuery, ...query }; + const resultLines = []; + let prevHunkOffset = 0; + for (let i = 0; i < hunks.length; i++) { + const hunk = hunks[i]; + let hunkResult; + const maxLine = lines.length - hunk.oldLines + fuzzFactor; + let toPos; + for (let maxErrors = 0; maxErrors <= fuzzFactor; maxErrors++) { + toPos = hunk.oldStart + prevHunkOffset - 1; + const iterator = distance_iterator_default(toPos, minLine, maxLine); + for (; toPos !== void 0; toPos = iterator()) { + hunkResult = applyHunk(hunk.lines, toPos, maxErrors); + if (hunkResult) { + break; + } + } + if (hunkResult) { + break; + } } - if (typeof query === "object" && query && !Array.isArray(query)) { - url.search = this.stringifyQuery(query); + if (!hunkResult) { + return false; } - return url.toString(); - } - /** - * Used as a callback for mutating the given `FinalRequestOptions` object. - */ - async prepareOptions(options) { - } - /** - * Used as a callback for mutating the given `RequestInit` object. - * - * This is useful for cases where you want to add certain headers based off of - * the request properties, e.g. `method` or `url`. - */ - async prepareRequest(request, { url, options }) { - } - get(path7, opts) { - return this.methodRequest("get", path7, opts); - } - post(path7, opts) { - return this.methodRequest("post", path7, opts); + for (let i2 = minLine; i2 < toPos; i2++) { + resultLines.push(lines[i2]); + } + for (let i2 = 0; i2 < hunkResult.patchedLines.length; i2++) { + const line = hunkResult.patchedLines[i2]; + resultLines.push(line); + } + minLine = hunkResult.oldLineLastI + 1; + prevHunkOffset = toPos + 1 - hunk.oldStart; } - patch(path7, opts) { - return this.methodRequest("patch", path7, opts); + for (let i = minLine; i < lines.length; i++) { + resultLines.push(lines[i]); } - put(path7, opts) { - return this.methodRequest("put", path7, opts); + return resultLines.join("\n"); +} + +// node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js +var INCLUDE_HEADERS = { + includeIndex: true, + includeUnderline: true, + includeFileHeaders: true +}; +function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + let optionsObj; + if (!options) { + optionsObj = {}; + } else if (typeof options === "function") { + optionsObj = { callback: options }; + } else { + optionsObj = options; } - delete(path7, opts) { - return this.methodRequest("delete", path7, opts); + if (typeof optionsObj.context === "undefined") { + optionsObj.context = 4; } - methodRequest(method, path7, opts) { - return this.request(Promise.resolve(opts).then((opts2) => { - return { method, path: path7, ...opts2 }; - })); + const context = optionsObj.context; + if (optionsObj.newlineIsToken) { + throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions"); } - request(options, remainingRetries = null) { - return new APIPromise3(this, this.makeRequest(options, remainingRetries, void 0)); + if (!optionsObj.callback) { + return diffLinesResultToPatch(diffLines(oldStr, newStr, optionsObj)); + } else { + const { callback } = optionsObj; + diffLines(oldStr, newStr, Object.assign(Object.assign({}, optionsObj), { callback: (diff) => { + const patch = diffLinesResultToPatch(diff); + callback(patch); + } })); } - async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { - const options = await optionsInput; - const maxRetries = options.maxRetries ?? this.maxRetries; - if (retriesRemaining == null) { - retriesRemaining = maxRetries; + function diffLinesResultToPatch(diff) { + if (!diff) { + return; } - await this.prepareOptions(options); - const { req, url, timeout } = await this.buildRequest(options, { - retryCount: maxRetries - retriesRemaining - }); - await this.prepareRequest(req, { url, options }); - const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0"); - const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`; - const startTime = Date.now(); - loggerFor3(this).debug(`[${requestLogID}] sending request`, formatRequestDetails3({ - retryOfRequestLogID, - method: options.method, - url, - options, - headers: req.headers - })); - if (options.signal?.aborted) { - throw new APIUserAbortError3(); + diff.push({ value: "", lines: [] }); + function contextLines(lines) { + return lines.map(function(entry) { + return " " + entry; + }); } - const controller = new AbortController(); - const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError3); - const headersTime = Date.now(); - if (response instanceof globalThis.Error) { - const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; - if (options.signal?.aborted) { - throw new APIUserAbortError3(); - } - const isTimeout = isAbortError3(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : "")); - if (retriesRemaining) { - loggerFor3(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`); - loggerFor3(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails3({ - retryOfRequestLogID, - url, - durationMs: headersTime - startTime, - message: response.message - })); - return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); - } - loggerFor3(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`); - loggerFor3(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails3({ - retryOfRequestLogID, - url, - durationMs: headersTime - startTime, - message: response.message - })); - if (isTimeout) { - throw new APIConnectionTimeoutError3(); + const hunks = []; + let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; + for (let i = 0; i < diff.length; i++) { + const current = diff[i], lines = current.lines || splitLines(current.value); + current.lines = lines; + if (current.added || current.removed) { + if (!oldRangeStart) { + const prev = diff[i - 1]; + oldRangeStart = oldLine; + newRangeStart = newLine; + if (prev) { + curRange = context > 0 ? contextLines(prev.lines.slice(-context)) : []; + oldRangeStart -= curRange.length; + newRangeStart -= curRange.length; + } + } + for (const line of lines) { + curRange.push((current.added ? "+" : "-") + line); + } + if (current.added) { + newLine += lines.length; + } else { + oldLine += lines.length; + } + } else { + if (oldRangeStart) { + if (lines.length <= context * 2 && i < diff.length - 2) { + for (const line of contextLines(lines)) { + curRange.push(line); + } + } else { + const contextSize = Math.min(lines.length, context); + for (const line of contextLines(lines.slice(0, contextSize))) { + curRange.push(line); + } + const hunk = { + oldStart: oldRangeStart, + oldLines: oldLine - oldRangeStart + contextSize, + newStart: newRangeStart, + newLines: newLine - newRangeStart + contextSize, + lines: curRange + }; + hunks.push(hunk); + oldRangeStart = 0; + newRangeStart = 0; + curRange = []; + } + } + oldLine += lines.length; + newLine += lines.length; } - throw new APIConnectionError3({ cause: response }); } - const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`; - if (!response.ok) { - const shouldRetry = await this.shouldRetry(response); - if (retriesRemaining && shouldRetry) { - const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`; - await CancelReadableStream3(response.body); - loggerFor3(this).info(`${responseInfo} - ${retryMessage2}`); - loggerFor3(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails3({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - durationMs: headersTime - startTime - })); - return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); + for (const hunk of hunks) { + for (let i = 0; i < hunk.lines.length; i++) { + if (hunk.lines[i].endsWith("\n")) { + hunk.lines[i] = hunk.lines[i].slice(0, -1); + } else { + hunk.lines.splice(i + 1, 0, "\\ No newline at end of file"); + i++; + } } - const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; - loggerFor3(this).info(`${responseInfo} - ${retryMessage}`); - const errText = await response.text().catch((err2) => castToError3(err2).message); - const errJSON = safeJSON3(errText); - const errMessage = errJSON ? void 0 : errText; - loggerFor3(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails3({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - message: errMessage, - durationMs: Date.now() - startTime - })); - const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); - throw err; } - loggerFor3(this).info(responseInfo); - loggerFor3(this).debug(`[${requestLogID}] response start`, formatRequestDetails3({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - durationMs: headersTime - startTime - })); - return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; - } - getAPIList(path7, Page2, opts) { - return this.requestAPIList(Page2, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path7, ...opts2 })) : { method: "get", path: path7, ...opts }); + return { + oldFileName, + newFileName, + oldHeader, + newHeader, + hunks + }; } - requestAPIList(Page2, options) { - const request = this.makeRequest(options, null, void 0); - return new PagePromise2(this, request, Page2); +} +function formatPatch(patch, headerOptions) { + if (!headerOptions) { + headerOptions = INCLUDE_HEADERS; } - async fetchWithTimeout(url, init, ms, controller) { - const { signal, method, ...options } = init || {}; - const abort = this._makeAbort(controller); - if (signal) - signal.addEventListener("abort", abort, { once: true }); - const timeout = setTimeout(abort, ms); - const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body; - const fetchOptions = { - signal: controller.signal, - ...isReadableBody ? { duplex: "half" } : {}, - method: "GET", - ...options - }; - if (method) { - fetchOptions.method = method.toUpperCase(); - } - try { - return await this.fetch.call(void 0, url, fetchOptions); - } finally { - clearTimeout(timeout); + if (Array.isArray(patch)) { + if (patch.length > 1 && !headerOptions.includeFileHeaders) { + throw new Error("Cannot omit file headers on a multi-file patch. (The result would be unparseable; how would a tool trying to apply the patch know which changes are to which file?)"); } + return patch.map((p) => formatPatch(p, headerOptions)).join("\n"); } - async shouldRetry(response) { - const shouldRetryHeader = response.headers.get("x-should-retry"); - if (shouldRetryHeader === "true") - return true; - if (shouldRetryHeader === "false") - return false; - if (response.status === 408) - return true; - if (response.status === 409) - return true; - if (response.status === 429) - return true; - if (response.status >= 500) - return true; - return false; + const ret = []; + if (headerOptions.includeIndex && patch.oldFileName == patch.newFileName) { + ret.push("Index: " + patch.oldFileName); } - async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { - let timeoutMillis; - const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms"); - if (retryAfterMillisHeader) { - const timeoutMs = parseFloat(retryAfterMillisHeader); - if (!Number.isNaN(timeoutMs)) { - timeoutMillis = timeoutMs; - } + if (headerOptions.includeUnderline) { + ret.push("==================================================================="); + } + if (headerOptions.includeFileHeaders) { + ret.push("--- " + patch.oldFileName + (typeof patch.oldHeader === "undefined" ? "" : " " + patch.oldHeader)); + ret.push("+++ " + patch.newFileName + (typeof patch.newHeader === "undefined" ? "" : " " + patch.newHeader)); + } + for (let i = 0; i < patch.hunks.length; i++) { + const hunk = patch.hunks[i]; + if (hunk.oldLines === 0) { + hunk.oldStart -= 1; } - const retryAfterHeader = responseHeaders?.get("retry-after"); - if (retryAfterHeader && !timeoutMillis) { - const timeoutSeconds = parseFloat(retryAfterHeader); - if (!Number.isNaN(timeoutSeconds)) { - timeoutMillis = timeoutSeconds * 1e3; - } else { - timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); - } + if (hunk.newLines === 0) { + hunk.newStart -= 1; } - if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1e3)) { - const maxRetries = options.maxRetries ?? this.maxRetries; - timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + ret.push("@@ -" + hunk.oldStart + "," + hunk.oldLines + " +" + hunk.newStart + "," + hunk.newLines + " @@"); + for (const line of hunk.lines) { + ret.push(line); } - await sleep3(timeoutMillis); - return this.makeRequest(options, retriesRemaining - 1, requestLogID); } - calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { - const initialRetryDelay = 0.5; - const maxRetryDelay = 8; - const numRetries = maxRetries - retriesRemaining; - const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); - const jitter = 1 - Math.random() * 0.25; - return sleepSeconds * jitter * 1e3; - } - async buildRequest(inputOptions, { retryCount = 0 } = {}) { - const options = { ...inputOptions }; - const { method, path: path7, query, defaultBaseURL } = options; - const url = this.buildURL(path7, query, defaultBaseURL); - if ("timeout" in options) - validatePositiveInteger3("timeout", options.timeout); - options.timeout = options.timeout ?? this.timeout; - const { bodyHeaders, body } = this.buildBody({ options }); - const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); - const req = { - method, - headers: reqHeaders, - ...options.signal && { signal: options.signal }, - ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" }, - ...body && { body }, - ...this.fetchOptions ?? {}, - ...options.fetchOptions ?? {} - }; - return { req, url, timeout: options.timeout }; + return ret.join("\n") + "\n"; +} +function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + if (typeof options === "function") { + options = { callback: options }; } - async buildHeaders({ options, method, bodyHeaders, retryCount }) { - let idempotencyHeaders = {}; - if (this.idempotencyHeader && method !== "get") { - if (!options.idempotencyKey) - options.idempotencyKey = this.defaultIdempotencyKey(); - idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; + if (!(options === null || options === void 0 ? void 0 : options.callback)) { + const patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); + if (!patchObj) { + return; } - const headers = buildHeaders3([ - idempotencyHeaders, - { - Accept: "application/json", - "User-Agent": this.getUserAgent(), - "X-Stainless-Retry-Count": String(retryCount), - ...options.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options.timeout / 1e3)) } : {}, - ...getPlatformHeaders3() - }, - await this.authHeaders(options), - this._options.defaultHeaders, - bodyHeaders, - options.headers - ]); - this.validateHeaders(headers); - return headers.values; - } - _makeAbort(controller) { - return () => controller.abort(); + return formatPatch(patchObj, options === null || options === void 0 ? void 0 : options.headerOptions); + } else { + const { callback } = options; + structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, Object.assign(Object.assign({}, options), { callback: (patchObj) => { + if (!patchObj) { + callback(void 0); + } else { + callback(formatPatch(patchObj, options.headerOptions)); + } + } })); } - buildBody({ options: { body, headers: rawHeaders } }) { - if (!body) { - return { bodyHeaders: void 0, body: void 0 }; - } - const headers = buildHeaders3([rawHeaders]); - if ( - // Pass raw type verbatim - ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && // Preserve legacy string encoding behavior for now - headers.values.has("content-type") || // `Blob` is superset of `File` - globalThis.Blob && body instanceof globalThis.Blob || // `FormData` -> `multipart/form-data` - body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded` - body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`) - globalThis.ReadableStream && body instanceof globalThis.ReadableStream - ) { - return { bodyHeaders: void 0, body }; - } else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) { - return { bodyHeaders: void 0, body: ReadableStreamFrom3(body) }; - } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") { - return { - bodyHeaders: { "content-type": "application/x-www-form-urlencoded" }, - body: this.stringifyQuery(body) - }; - } else { - return __classPrivateFieldGet3(this, _Stainless_encoder, "f").call(this, { body, headers }); - } +} +function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { + return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); +} +function splitLines(text) { + const hasTrailingNl = text.endsWith("\n"); + const result = text.split("\n").map((line) => line + "\n"); + if (hasTrailingNl) { + result.pop(); + } else { + result.push(result.pop().slice(0, -1)); } -}; -_a = Stainless, _Stainless_encoder = /* @__PURE__ */ new WeakMap(), _Stainless_instances = /* @__PURE__ */ new WeakSet(), _Stainless_baseURLOverridden = function _Stainless_baseURLOverridden2() { - return this.baseURL !== environments[this._options.environment || "production"]; -}; -Stainless.Stainless = _a; -Stainless.DEFAULT_TIMEOUT = 6e4; -Stainless.StainlessError = StainlessError; -Stainless.APIError = APIError3; -Stainless.APIConnectionError = APIConnectionError3; -Stainless.APIConnectionTimeoutError = APIConnectionTimeoutError3; -Stainless.APIUserAbortError = APIUserAbortError3; -Stainless.NotFoundError = NotFoundError3; -Stainless.ConflictError = ConflictError3; -Stainless.RateLimitError = RateLimitError3; -Stainless.BadRequestError = BadRequestError3; -Stainless.AuthenticationError = AuthenticationError3; -Stainless.InternalServerError = InternalServerError3; -Stainless.PermissionDeniedError = PermissionDeniedError3; -Stainless.UnprocessableEntityError = UnprocessableEntityError3; -Stainless.toFile = toFile3; -Stainless.unwrapFile = unwrapFile; -Stainless.Projects = Projects5; -Stainless.Builds = Builds2; -Stainless.Orgs = Orgs3; -Stainless.User = User; + return result; +} // package.json var package_default = { @@ -20077,7 +20094,8 @@ function wrapAction(actionType, fn) { actionType, successOrError: { result: "success" } }); - } catch (error) { + } catch (rawError) { + const error = maybeToActionError(rawError); logger.fatal("Error in action:", error); if (stainless) { await maybeReportResult({ diff --git a/src/checkoutPRRef.ts b/src/checkoutPRRef.ts index f85e20e..38c78dc 100644 --- a/src/checkoutPRRef.ts +++ b/src/checkoutPRRef.ts @@ -1,11 +1,14 @@ import spawn from "nano-spawn"; import { getInput } from "./compat"; import { getMergeBase, saveConfig } from "./config"; +import { ActionError } from "./error"; import { logger } from "./logger"; function assertRef(ref: string): asserts ref is "base" | "head" { if (ref !== "base" && ref !== "head") { - throw new Error(`Expected ref to be 'base' or 'head', but was ${ref}`); + throw new ActionError( + `Expected ref to be 'base' or 'head', but was ${ref}`, + ); } } @@ -32,7 +35,7 @@ async function main() { // Callers come in from checkout-pr-ref against base; save the config. const { hasOAS, savedSha } = await saveConfig({ oasPath, configPath }); if (!hasOAS) { - throw new Error(`Expected OpenAPI spec at ${oasPath}.`); + throw new ActionError(`Expected OpenAPI spec at ${oasPath}.`); } if (savedSha !== null && savedSha !== mergeBaseSha) { logger.warn( diff --git a/src/error.ts b/src/error.ts new file mode 100644 index 0000000..906d18f --- /dev/null +++ b/src/error.ts @@ -0,0 +1,23 @@ +import Stainless from "@stainless-api/sdk"; + +/** An expected failure (invalid input, missing files, auth failures) */ +export class ActionError extends Error { + constructor(message: string, options?: ErrorOptions) { + super(message, options); + this.name = "ActionError"; + } +} + +/** Mark user-facing Stainless API errors as expected failures. */ +export function maybeToActionError(error: unknown): unknown { + if ( + error instanceof Stainless.BadRequestError || + error instanceof Stainless.AuthenticationError || + error instanceof Stainless.PermissionDeniedError || + error instanceof Stainless.NotFoundError || + error instanceof Stainless.UnprocessableEntityError + ) { + return new ActionError(error.message, { cause: error }); + } + return error; +} diff --git a/src/index.ts b/src/index.ts index 8a8109f..34eeb11 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,6 +3,7 @@ import { getStainlessClient } from "./stainless"; import { readFileSync, writeFileSync } from "node:fs"; import YAML from "yaml"; import { getBooleanInput, getInput, getStainlessAuth } from "./compat"; +import { ActionError, maybeToActionError } from "./error"; import { logger } from "./logger"; // https://www.conventionalcommits.org/en/v1.0.0/ @@ -30,14 +31,14 @@ export async function main() { if (configPath && guessConfig) { const errorMsg = "Can't set both configPath and guessConfig"; logger.error(errorMsg); - throw Error(errorMsg); + throw new ActionError(errorMsg); } if (commitMessage && !isValidConventionalCommitMessage(commitMessage)) { const errorMsg = "Invalid commit message format. Please follow the Conventional Commits format: https://www.conventionalcommits.org/en/v1.0.0/"; logger.error(errorMsg); - throw Error(errorMsg); + throw new ActionError(errorMsg); } if (!projectName) { @@ -48,7 +49,7 @@ export async function main() { if (projects.data.length === 0) { const errorMsg = "No projects found. Please create a project first."; logger.error(errorMsg); - throw Error(errorMsg); + throw new ActionError(errorMsg); } projectName = projects.data[0]!.slug; if (projects.data.length > 1) { @@ -77,7 +78,7 @@ export async function main() { response.errors, )} See more details in the Stainless Studio.`; logger.error(errorMsg); - throw Error(errorMsg); + throw new ActionError(errorMsg); } logger.info("Uploaded!"); @@ -85,7 +86,7 @@ export async function main() { if (!response.decoratedSpec) { const errorMsg = "Failed to get decorated spec"; logger.error(errorMsg); - throw Error(errorMsg); + throw new ActionError(errorMsg); } // Decorated spec is currently always YAML, so convert it to JSON if needed. if (!(outputPath.endsWith(".yml") || outputPath.endsWith(".yaml"))) { @@ -206,7 +207,8 @@ async function uploadSpecAndConfig( } if (require.main === module) { - main().catch((err) => { + main().catch((rawErr) => { + const err = maybeToActionError(rawErr); logger.fatal("Fatal error:", err); process.exit(1); }); diff --git a/src/logger.test.ts b/src/logger.test.ts index 09a2226..2d3dd7e 100644 --- a/src/logger.test.ts +++ b/src/logger.test.ts @@ -8,6 +8,7 @@ import { type Mock, } from "vitest"; import { logging, type Logging } from "./compat/logging"; +import { ActionError } from "./error"; import { createLogger, type LogLevel } from "./logger"; vi.mock("./compat/logging", async () => { @@ -240,7 +241,7 @@ describe("logger", () => { }); describe("fatal", () => { - it("logs error and bug report URL", () => { + it("logs error and bug report URL for unexpected errors", () => { const { logger } = setupLogger("error"); logger.fatal("Something broke", new Error("test error")); @@ -253,6 +254,16 @@ describe("logger", () => { ); }); + it("does not show bug report URL for ActionError", () => { + const { logger } = setupLogger("error"); + + logger.fatal("Something broke", new ActionError("expected failure")); + + const output = stderrSpy.mock.calls.map((c) => c[0]).join(""); + expect(output).toContain("Something broke"); + expect(output).not.toContain("This is a bug"); + }); + it("calls provider error annotation", () => { const { logger, provider } = setupLogger("error"); diff --git a/src/logger.ts b/src/logger.ts index 09d5501..0f5e284 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -5,6 +5,7 @@ import { getInput } from "./compat/input"; import { logging, type Logging } from "./compat/logging"; +import { ActionError } from "./error"; export type LogLevel = "debug" | "info" | "warn" | "error" | "off"; @@ -135,9 +136,12 @@ function createLoggerImpl(logContext: LogContext): Logger { fatal(message: string, ...args: unknown[]): void { errorFn(message, ...args); - process.stderr.write( - `\nThis is a bug. Please report it at ${BUG_REPORT_URL}\n`, - ); + const isActionError = args.some((arg) => arg instanceof ActionError); + if (!isActionError) { + process.stderr.write( + `\nThis is a bug. Please report it at ${BUG_REPORT_URL}\n`, + ); + } }, child(childContext: string): Logger { diff --git a/src/wrapAction.ts b/src/wrapAction.ts index 0c71fdb..35cfb85 100644 --- a/src/wrapAction.ts +++ b/src/wrapAction.ts @@ -1,6 +1,7 @@ import Stainless from "@stainless-api/sdk"; import { getInput } from "./compat/input"; import { getStainlessAuth } from "./compat"; +import { maybeToActionError } from "./error"; import { addFetch401Retries, createAutoRefreshFetch, @@ -49,7 +50,8 @@ export function wrapAction( actionType, successOrError: { result: "success" }, }); - } catch (error) { + } catch (rawError) { + const error = maybeToActionError(rawError); logger.fatal("Error in action:", error); if (stainless) { await maybeReportResult({