autumn-js
Version:
Autumn JS Library
1,755 lines (1,722 loc) • 1.11 MB
JavaScript
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/backend/index.ts
var index_exports = {};
__export(index_exports, {
autumnHandler: () => autumnHandler,
backendError: () => backendError,
backendSuccess: () => backendSuccess,
buildRouter: () => buildRouter,
createCoreHandler: () => createCoreHandler,
isBackendResult: () => isBackendResult,
routeConfigs: () => routeConfigs,
sanitizeBody: () => sanitizeBody,
secretKeyCheck: () => secretKeyCheck
});
module.exports = __toCommonJS(index_exports);
// ../sdk/src/lib/url.ts
var hasOwn = Object.prototype.hasOwnProperty;
function pathToFunc(pathPattern, options) {
const paramRE = /\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g;
return function buildURLPath(params = {}) {
return pathPattern.replace(paramRE, function(_, placeholder) {
if (!hasOwn.call(params, placeholder)) {
throw new Error(`Parameter '${placeholder}' is required`);
}
const value = params[placeholder];
if (typeof value !== "string" && typeof value !== "number") {
throw new Error(
`Parameter '${placeholder}' must be a string or number`
);
}
return options?.charEncoding === "percent" ? encodeURIComponent(`${value}`) : `${value}`;
}).replace(/^\/+/, "");
};
}
// ../sdk/src/lib/config.ts
var ServerList = [
/**
* Production server
*/
"https://api.useautumn.com"
];
function serverURLFromOptions(options) {
let serverURL = options.serverURL;
const params = {};
if (!serverURL) {
const serverIdx = options.serverIdx ?? 0;
if (serverIdx < 0 || serverIdx >= ServerList.length) {
throw new Error(`Invalid server index ${serverIdx}`);
}
serverURL = ServerList[serverIdx] || "";
}
const u = pathToFunc(serverURL)(params);
return new URL(u);
}
var SDK_METADATA = {
language: "typescript",
openapiDocVersion: "2.3.0",
sdkVersion: "0.10.17",
genVersion: "2.882.0",
userAgent: "speakeasy-sdk/typescript 0.10.17 2.882.0 2.3.0 @useautumn/sdk"
};
// ../sdk/src/lib/http.ts
var DEFAULT_FETCHER = (input, init) => {
if (init == null) {
return fetch(input);
} else {
return fetch(input, init);
}
};
var HTTPClient = class _HTTPClient {
constructor(options = {}) {
this.options = options;
this.fetcher = options.fetcher || DEFAULT_FETCHER;
}
fetcher;
requestHooks = [];
requestErrorHooks = [];
responseHooks = [];
async request(request) {
let req = request;
for (const hook of this.requestHooks) {
const nextRequest = await hook(req);
if (nextRequest) {
req = nextRequest;
}
}
try {
const res = await this.fetcher(req);
for (const hook of this.responseHooks) {
await hook(res, req);
}
return res;
} catch (err) {
for (const hook of this.requestErrorHooks) {
await hook(err, req);
}
throw err;
}
}
addHook(...args) {
if (args[0] === "beforeRequest") {
this.requestHooks.push(args[1]);
} else if (args[0] === "requestError") {
this.requestErrorHooks.push(args[1]);
} else if (args[0] === "response") {
this.responseHooks.push(args[1]);
} else {
throw new Error(`Invalid hook type: ${args[0]}`);
}
return this;
}
removeHook(...args) {
let target;
if (args[0] === "beforeRequest") {
target = this.requestHooks;
} else if (args[0] === "requestError") {
target = this.requestErrorHooks;
} else if (args[0] === "response") {
target = this.responseHooks;
} else {
throw new Error(`Invalid hook type: ${args[0]}`);
}
const index = target.findIndex((v) => v === args[1]);
if (index >= 0) {
target.splice(index, 1);
}
return this;
}
clone() {
const child = new _HTTPClient(this.options);
child.requestHooks = this.requestHooks.slice();
child.requestErrorHooks = this.requestErrorHooks.slice();
child.responseHooks = this.responseHooks.slice();
return child;
}
};
var mediaParamSeparator = /\s*;\s*/g;
function matchContentType(response, pattern) {
if (pattern === "*") {
return true;
}
let contentType = response.headers.get("content-type")?.trim() || "application/octet-stream";
contentType = contentType.toLowerCase();
const wantParts = pattern.toLowerCase().trim().split(mediaParamSeparator);
const [wantType = "", ...wantParams] = wantParts;
if (wantType.split("/").length !== 2) {
return false;
}
const gotParts = contentType.split(mediaParamSeparator);
const [gotType = "", ...gotParams] = gotParts;
const [type = "", subtype = ""] = gotType.split("/");
if (!type || !subtype) {
return false;
}
if (wantType !== "*/*" && gotType !== wantType && `${type}/*` !== wantType && `*/${subtype}` !== wantType) {
return false;
}
if (gotParams.length < wantParams.length) {
return false;
}
const params = new Set(gotParams);
for (const wantParam of wantParams) {
if (!params.has(wantParam)) {
return false;
}
}
return true;
}
var codeRangeRE = new RegExp("^[0-9]xx$", "i");
function matchStatusCode(response, codes) {
const actual = `${response.status}`;
const expectedCodes = Array.isArray(codes) ? codes : [codes];
if (!expectedCodes.length) {
return false;
}
return expectedCodes.some((ec) => {
const code = `${ec}`;
if (code === "default") {
return true;
}
if (!codeRangeRE.test(`${code}`)) {
return code === actual;
}
const expectFamily = code.charAt(0);
if (!expectFamily) {
throw new Error("Invalid status code range");
}
const actualFamily = actual.charAt(0);
if (!actualFamily) {
throw new Error(`Invalid response status code: ${actual}`);
}
return actualFamily === expectFamily;
});
}
function matchResponse(response, code, contentTypePattern) {
return matchStatusCode(response, code) && matchContentType(response, contentTypePattern);
}
function isConnectionError(err) {
if (typeof err !== "object" || err == null) {
return false;
}
const isBrowserErr = err instanceof TypeError && err.message.toLowerCase().startsWith("failed to fetch");
const isNodeErr = err instanceof TypeError && err.message.toLowerCase().startsWith("fetch failed");
const isBunErr = "name" in err && err.name === "ConnectionError";
const isGenericErr = "code" in err && typeof err.code === "string" && err.code.toLowerCase() === "econnreset";
return isBrowserErr || isNodeErr || isGenericErr || isBunErr;
}
function isTimeoutError(err) {
if (typeof err !== "object" || err == null) {
return false;
}
const isNative = "name" in err && err.name === "TimeoutError";
const isLegacyNative = "code" in err && err.code === 23;
const isGenericErr = "code" in err && typeof err.code === "string" && err.code.toLowerCase() === "econnaborted";
return isNative || isLegacyNative || isGenericErr;
}
function isAbortError(err) {
if (typeof err !== "object" || err == null) {
return false;
}
const isNative = "name" in err && err.name === "AbortError";
const isLegacyNative = "code" in err && err.code === 20;
const isGenericErr = "code" in err && typeof err.code === "string" && err.code.toLowerCase() === "econnaborted";
return isNative || isLegacyNative || isGenericErr;
}
// ../sdk/src/funcs/batch-track.ts
var z66 = __toESM(require("zod/v4-mini"), 1);
// ../sdk/src/lib/base64.ts
var z = __toESM(require("zod/v4-mini"), 1);
function bytesToBase64(u8arr) {
return btoa(String.fromCodePoint(...u8arr));
}
function bytesFromBase64(encoded) {
return Uint8Array.from(atob(encoded), (c) => c.charCodeAt(0));
}
function stringToBytes(str) {
return new TextEncoder().encode(str);
}
function stringToBase64(str) {
return bytesToBase64(stringToBytes(str));
}
var zodOutbound = z.union([
z.custom((x) => x instanceof Uint8Array),
z.pipe(z.string(), z.transform(stringToBytes))
]);
var zodInbound = z.union([
z.custom((x) => x instanceof Uint8Array),
z.pipe(z.string(), z.transform(bytesFromBase64))
]);
// ../sdk/src/lib/is-plain-object.ts
function isPlainObject(value) {
if (typeof value !== "object" || value === null) {
return false;
}
const prototype = Object.getPrototypeOf(value);
return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
}
// ../sdk/src/lib/encodings.ts
var EncodingError = class extends Error {
constructor(message) {
super(message);
this.name = "EncodingError";
}
};
function formEncoder(sep) {
return (key, value, options) => {
let out = "";
const pairs = options?.explode ? explode(key, value) : [[key, value]];
if (pairs.every(([_, v]) => v == null)) {
return;
}
const encodeString = (v) => {
return options?.charEncoding === "percent" ? encodeURIComponent(v) : v;
};
const encodeValue = (v) => encodeString(serializeValue(v));
const encodedSep = encodeString(sep);
pairs.forEach(([pk, pv]) => {
let tmp = "";
let encValue = null;
if (pv == null) {
return;
} else if (Array.isArray(pv)) {
encValue = mapDefined(pv, (v) => `${encodeValue(v)}`)?.join(encodedSep);
} else if (isPlainObject(pv)) {
encValue = mapDefinedEntries(Object.entries(pv), ([k, v]) => {
return `${encodeString(k)}${encodedSep}${encodeValue(v)}`;
})?.join(encodedSep);
} else {
encValue = `${encodeValue(pv)}`;
}
if (encValue == null) {
return;
}
tmp = `${encodeString(pk)}=${encValue}`;
if (!tmp || tmp === "=") {
return;
}
out += `&${tmp}`;
});
return out.slice(1);
};
}
var encodeForm = formEncoder(",");
var encodeSpaceDelimited = formEncoder(" ");
var encodePipeDelimited = formEncoder("|");
function encodeDeepObject(key, value, options) {
if (value == null) {
return;
}
if (!isPlainObject(value)) {
throw new EncodingError(
`Value of parameter '${key}' which uses deepObject encoding must be an object or null`
);
}
return encodeDeepObjectObject(key, value, options);
}
function encodeDeepObjectObject(key, value, options) {
if (value == null) {
return;
}
let out = "";
const encodeString = (v) => {
return options?.charEncoding === "percent" ? encodeURIComponent(v) : v;
};
if (!isPlainObject(value)) {
throw new EncodingError(`Expected parameter '${key}' to be an object.`);
}
Object.entries(value).forEach(([ck, cv]) => {
if (cv == null) {
return;
}
const pk = `${key}[${ck}]`;
if (isPlainObject(cv)) {
const objOut = encodeDeepObjectObject(pk, cv, options);
out += objOut == null ? "" : `&${objOut}`;
return;
}
const pairs = Array.isArray(cv) ? cv : [cv];
const encoded = mapDefined(pairs, (v) => {
return `${encodeString(pk)}=${encodeString(serializeValue(v))}`;
})?.join("&");
out += encoded == null ? "" : `&${encoded}`;
});
return out.slice(1);
}
function encodeJSON(key, value, options) {
if (typeof value === "undefined") {
return;
}
const encodeString = (v) => {
return options?.charEncoding === "percent" ? encodeURIComponent(v) : v;
};
const encVal = encodeString(JSON.stringify(value, jsonReplacer));
return options?.explode ? encVal : `${encodeString(key)}=${encVal}`;
}
var encodeSimple = (key, value, options) => {
let out = "";
const pairs = options?.explode ? explode(key, value) : [[key, value]];
if (pairs.every(([_, v]) => v == null)) {
return;
}
const encodeString = (v) => {
return options?.charEncoding === "percent" ? encodeURIComponent(v) : v;
};
const encodeValue = (v) => encodeString(serializeValue(v));
pairs.forEach(([pk, pv]) => {
let tmp = "";
if (pv == null) {
return;
} else if (Array.isArray(pv)) {
tmp = mapDefined(pv, (v) => `${encodeValue(v)}`)?.join(",");
} else if (isPlainObject(pv)) {
const mapped = mapDefinedEntries(Object.entries(pv), ([k, v]) => {
return `,${encodeString(k)},${encodeValue(v)}`;
});
tmp = mapped?.join("").slice(1);
} else {
const k = options?.explode && isPlainObject(value) ? `${pk}=` : "";
tmp = `${k}${encodeValue(pv)}`;
}
out += tmp ? `,${tmp}` : "";
});
return out.slice(1);
};
function explode(key, value) {
if (Array.isArray(value)) {
return value.map((v) => [key, v]);
} else if (isPlainObject(value)) {
const o = value ?? {};
return Object.entries(o).map(([k, v]) => [k, v]);
} else {
return [[key, value]];
}
}
function serializeValue(value) {
if (value == null) {
return "";
} else if (value instanceof Date) {
return value.toISOString();
} else if (value instanceof Uint8Array) {
return bytesToBase64(value);
} else if (typeof value === "object") {
return JSON.stringify(value, jsonReplacer);
}
return `${value}`;
}
function jsonReplacer(_, value) {
if (value instanceof Uint8Array) {
return bytesToBase64(value);
} else {
return value;
}
}
function mapDefined(inp, mapper) {
const res = inp.reduce((acc, v) => {
if (v == null) {
return acc;
}
const m = mapper(v);
if (m == null) {
return acc;
}
acc.push(m);
return acc;
}, []);
return res.length ? res : null;
}
function mapDefinedEntries(inp, mapper) {
const acc = [];
for (const [k, v] of inp) {
if (v == null) {
continue;
}
const m = mapper([k, v]);
if (m == null) {
continue;
}
acc.push(m);
}
return acc.length ? acc : null;
}
function queryJoin(...args) {
return args.filter(Boolean).join("&");
}
function queryEncoder(f) {
const bulkEncode = function(values, options) {
const opts = {
...options,
explode: options?.explode ?? true,
charEncoding: options?.charEncoding ?? "percent"
};
const allowEmptySet = new Set(options?.allowEmptyValue ?? []);
const encoded = Object.entries(values).map(([key, value]) => {
if (allowEmptySet.has(key)) {
if (value === void 0 || value === null || value === "" || Array.isArray(value) && value.length === 0) {
return `${encodeURIComponent(key)}=`;
}
}
return f(key, value, opts);
});
return queryJoin(...encoded);
};
return bulkEncode;
}
var encodeJSONQuery = queryEncoder(encodeJSON);
var encodeFormQuery = queryEncoder(encodeForm);
var encodeSpaceDelimitedQuery = queryEncoder(encodeSpaceDelimited);
var encodePipeDelimitedQuery = queryEncoder(encodePipeDelimited);
var encodeDeepObjectQuery = queryEncoder(encodeDeepObject);
// ../sdk/src/models/autumn-error.ts
var AutumnError = class extends Error {
/** HTTP status code */
statusCode;
/** HTTP body */
body;
/** HTTP headers */
headers;
/** HTTP content type */
contentType;
/** Raw response */
rawResponse;
constructor(message, httpMeta) {
super(message);
this.statusCode = httpMeta.response.status;
this.body = httpMeta.body;
this.headers = httpMeta.response.headers;
this.contentType = httpMeta.response.headers.get("content-type") || "";
this.rawResponse = httpMeta.response;
this.name = "AutumnError";
}
};
// ../sdk/src/models/autumn-default-error.ts
var AutumnDefaultError = class extends AutumnError {
constructor(message, httpMeta) {
if (message) {
message += `: `;
}
message += `Status ${httpMeta.response.status}`;
const contentType = httpMeta.response.headers.get("content-type") || `""`;
if (contentType !== "application/json") {
message += ` Content-Type ${contentType.includes(" ") ? `"${contentType}"` : contentType}`;
}
const body = httpMeta.body || `""`;
message += body.length > 100 ? "\n" : ". ";
let bodyDisplay = body;
if (body.length > 1e4) {
const truncated = body.substring(0, 1e4);
const remaining = body.length - 1e4;
bodyDisplay = `${truncated}...and ${remaining} more chars`;
}
message += `Body: ${bodyDisplay}`;
message = message.trim();
super(message, httpMeta);
this.name = "AutumnDefaultError";
}
};
// ../sdk/src/models/response-validation-error.ts
var z3 = __toESM(require("zod/v4/core"), 1);
// ../sdk/src/models/sdk-validation-error.ts
var z2 = __toESM(require("zod/v4/core"), 1);
var SDKValidationError = class extends Error {
/**
* The raw value that failed validation.
*/
rawValue;
/**
* The raw message that failed validation.
*/
rawMessage;
// Allows for backwards compatibility for `instanceof` checks of `ResponseValidationError`
static [Symbol.hasInstance](instance) {
if (!(instance instanceof Error)) return false;
if (!("rawValue" in instance)) return false;
if (!("rawMessage" in instance)) return false;
if (!("pretty" in instance)) return false;
if (typeof instance.pretty !== "function") return false;
return true;
}
constructor(message, cause, rawValue) {
super(`${message}: ${cause}`);
this.name = "SDKValidationError";
this.cause = cause;
this.rawValue = rawValue;
this.rawMessage = message;
}
/**
* Return a pretty-formatted error message if the underlying validation error
* is a ZodError or some other recognized error type, otherwise return the
* default error message.
*/
pretty() {
if (this.cause instanceof z2.$ZodError) {
return `${this.rawMessage}
${formatZodError(this.cause)}`;
} else {
return this.toString();
}
}
};
function formatZodError(err) {
return z2.prettifyError(err);
}
// ../sdk/src/models/response-validation-error.ts
var ResponseValidationError = class extends AutumnError {
/**
* The raw value that failed validation.
*/
rawValue;
/**
* The raw message that failed validation.
*/
rawMessage;
constructor(message, extra) {
super(message, extra);
this.name = "ResponseValidationError";
this.cause = extra.cause;
this.rawValue = extra.rawValue;
this.rawMessage = extra.rawMessage;
}
/**
* Return a pretty-formatted error message if the underlying validation error
* is a ZodError or some other recognized error type, otherwise return the
* default error message.
*/
pretty() {
if (this.cause instanceof z3.$ZodError) {
return `${this.rawMessage}
${formatZodError(this.cause)}`;
} else {
return this.toString();
}
}
};
// ../sdk/src/types/fp.ts
function OK(value) {
return { ok: true, value };
}
function ERR(error) {
return { ok: false, error };
}
async function unwrapAsync(pr) {
const r = await pr;
if (!r.ok) {
throw r.error;
}
return r.value;
}
// ../sdk/src/lib/matchers.ts
var DEFAULT_CONTENT_TYPES = {
jsonl: "application/jsonl",
json: "application/json",
text: "text/plain",
bytes: "application/octet-stream",
stream: "application/octet-stream",
sse: "text/event-stream",
nil: "*",
fail: "*"
};
function json(codes, schema, options) {
return { ...options, enc: "json", codes, schema };
}
function fail(codes) {
return { enc: "fail", codes };
}
function match(...matchers) {
return async function matchFunc(response, request, options) {
let raw;
let matcher;
for (const match2 of matchers) {
const { codes } = match2;
const ctpattern = "ctype" in match2 ? match2.ctype : DEFAULT_CONTENT_TYPES[match2.enc];
if (ctpattern && matchResponse(response, codes, ctpattern)) {
matcher = match2;
break;
} else if (!ctpattern && matchStatusCode(response, codes)) {
matcher = match2;
break;
}
}
if (!matcher) {
return [{
ok: false,
error: new AutumnDefaultError("Unexpected Status or Content-Type", {
response,
request,
body: await response.text().catch(() => "")
})
}, raw];
}
const encoding = matcher.enc;
let body = "";
switch (encoding) {
case "json":
body = await response.text();
raw = JSON.parse(body);
break;
case "jsonl":
raw = response.body;
break;
case "bytes":
raw = new Uint8Array(await response.arrayBuffer());
break;
case "stream":
raw = response.body;
break;
case "text":
body = await response.text();
raw = body;
break;
case "sse":
raw = response.body;
break;
case "nil":
body = await response.text();
raw = void 0;
break;
case "fail":
body = await response.text();
raw = body;
break;
default:
throw new Error(
`Unsupported response type: ${encoding}`
);
}
if (matcher.enc === "fail") {
return [{
ok: false,
error: new AutumnDefaultError("API error occurred", {
request,
response,
body
})
}, raw];
}
const resultKey = matcher.key || options?.resultKey;
let data;
if ("err" in matcher) {
data = {
...options?.extraFields,
...matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null,
...isPlainObject(raw) ? raw : null,
request$: request,
response$: response,
body$: body
};
} else if (resultKey) {
data = {
...options?.extraFields,
...matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null,
[resultKey]: raw
};
} else if (matcher.hdrs) {
data = {
...options?.extraFields,
...matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null,
...isPlainObject(raw) ? raw : null
};
} else {
data = raw;
}
if ("err" in matcher) {
const result = safeParseResponse(
data,
(v) => matcher.schema.parse(v),
"Response validation failed",
{ request, response, body }
);
return [result.ok ? { ok: false, error: result.value } : result, raw];
} else {
return [
safeParseResponse(
data,
(v) => matcher.schema.parse(v),
"Response validation failed",
{ request, response, body }
),
raw
];
}
};
}
var headerValRE = /, */;
function unpackHeaders(headers) {
const out = {};
for (const [k, v] of headers.entries()) {
out[k] = v.split(headerValRE);
}
return out;
}
function safeParseResponse(rawValue, fn, errorMessage, httpMeta) {
try {
return OK(fn(rawValue));
} catch (err) {
return ERR(
new ResponseValidationError(errorMessage, {
cause: err,
rawValue,
rawMessage: errorMessage,
...httpMeta
})
);
}
}
// ../sdk/src/lib/primitives.ts
function remap(inp, mappings) {
let out = {};
if (!Object.keys(mappings).length) {
out = inp;
return out;
}
for (const [k, v] of Object.entries(inp)) {
const j = mappings[k];
if (j === null) {
continue;
}
out[j ?? k] = v;
}
return out;
}
function compactMap(values) {
const out = {};
for (const [k, v] of Object.entries(values)) {
if (typeof v !== "undefined") {
out[k] = v;
}
}
return out;
}
// ../sdk/src/lib/schemas.ts
var z4 = __toESM(require("zod/v4-mini"), 1);
function safeParse(rawValue, fn, errorMessage) {
try {
return OK(fn(rawValue));
} catch (err) {
return ERR(new SDKValidationError(errorMessage, err, rawValue));
}
}
// ../sdk/src/lib/env.ts
var z5 = __toESM(require("zod/v4-mini"), 1);
// ../sdk/src/lib/dlv.ts
function dlv(obj, key, def, p, undef) {
key = Array.isArray(key) ? key : key.split(".");
for (p = 0; p < key.length; p++) {
const k = key[p];
obj = k != null && obj ? obj[k] : undef;
}
return obj === undef ? def : obj;
}
// ../sdk/src/lib/env.ts
var envSchema = z5.object({
AUTUMN_SECRET_KEY: z5.optional(z5.string()),
AUTUMN_X_API_VERSION: z5._default(z5.string(), "2.3.0"),
AUTUMN_FAIL_OPEN: z5.pipe(
z5._default(z5.enum(["true", "false"]), "true"),
z5.transform((v) => v === "true")
),
AUTUMN_DEBUG: z5.optional(z5.coerce.boolean())
});
function isDeno() {
if ("Deno" in globalThis) {
return true;
}
return false;
}
var envMemo = void 0;
function env() {
if (envMemo) {
return envMemo;
}
let envObject = {};
if (isDeno()) {
envObject = globalThis.Deno?.env?.toObject?.() ?? {};
} else {
envObject = dlv(globalThis, "process.env") ?? {};
}
envMemo = envSchema.parse(envObject);
return envMemo;
}
function fillGlobals(options) {
const clone = { ...options };
const envVars = env();
if (typeof envVars.AUTUMN_X_API_VERSION !== "undefined") {
clone.xApiVersion ??= envVars.AUTUMN_X_API_VERSION;
}
if (typeof envVars.AUTUMN_FAIL_OPEN !== "undefined") {
clone.failOpen ??= envVars.AUTUMN_FAIL_OPEN;
}
return clone;
}
// ../sdk/src/lib/security.ts
var SecurityError = class _SecurityError extends Error {
constructor(code, message) {
super(message);
this.code = code;
this.name = "SecurityError";
}
static incomplete() {
return new _SecurityError(
"incomplete" /* Incomplete */,
"Security requirements not met in order to perform the operation"
);
}
static unrecognizedType(type) {
return new _SecurityError(
"unrecognized_security_type" /* UnrecognisedSecurityType */,
`Unrecognised security type: ${type}`
);
}
};
function resolveSecurity(...options) {
const state = {
basic: {},
headers: {},
queryParams: {},
cookies: {},
oauth2: { type: "none" }
};
const option = options.find((opts) => {
return opts.every((o) => {
if (o.value == null) {
return false;
} else if (o.type === "http:basic") {
return o.value.username != null || o.value.password != null;
} else if (o.type === "http:custom") {
return null;
} else if (o.type === "oauth2:password") {
return typeof o.value === "string" && !!o.value;
} else if (o.type === "oauth2:client_credentials") {
if (typeof o.value == "string") {
return !!o.value;
}
return o.value.clientID != null || o.value.clientSecret != null;
} else if (typeof o.value === "string") {
return !!o.value;
} else {
throw new Error(
`Unrecognized security type: ${o.type} (value type: ${typeof o.value})`
);
}
});
});
if (option == null) {
return null;
}
option.forEach((spec) => {
if (spec.value == null) {
return;
}
const { type } = spec;
switch (type) {
case "apiKey:header":
state.headers[spec.fieldName] = spec.value;
break;
case "apiKey:query":
state.queryParams[spec.fieldName] = spec.value;
break;
case "apiKey:cookie":
state.cookies[spec.fieldName] = spec.value;
break;
case "http:basic":
applyBasic(state, spec);
break;
case "http:custom":
break;
case "http:bearer":
applyBearer(state, spec);
break;
case "oauth2":
applyBearer(state, spec);
break;
case "oauth2:password":
applyBearer(state, spec);
break;
case "oauth2:client_credentials":
break;
case "openIdConnect":
applyBearer(state, spec);
break;
default:
throw SecurityError.unrecognizedType((spec, type));
}
});
return state;
}
function applyBasic(state, spec) {
if (spec.value == null) {
return;
}
state.basic = spec.value;
}
function applyBearer(state, spec) {
if (typeof spec.value !== "string" || !spec.value) {
return;
}
let value = spec.value;
if (value.slice(0, 7).toLowerCase() !== "bearer ") {
value = `Bearer ${value}`;
}
if (spec.fieldName !== void 0) {
state.headers[spec.fieldName] = value;
}
}
function resolveGlobalSecurity(security, allowedFields) {
let inputs = [
[
{
fieldName: "Authorization",
type: "http:bearer",
value: security?.secretKey ?? env().AUTUMN_SECRET_KEY
}
]
];
if (allowedFields) {
inputs = allowedFields.map((i) => {
if (i < 0 || i >= inputs.length) {
throw new RangeError(`invalid allowedFields index ${i}`);
}
return inputs[i];
});
}
return resolveSecurity(...inputs);
}
async function extractSecurity(sec) {
if (sec == null) {
return;
}
return typeof sec === "function" ? sec() : sec;
}
// ../sdk/src/models/aggregate-events-op.ts
var z8 = __toESM(require("zod/v4-mini"), 1);
// ../sdk/src/types/primitives.ts
var z6 = __toESM(require("zod/v4-mini"), 1);
// ../sdk/src/types/unrecognized.ts
function unrecognized(value) {
globalCount++;
return value;
}
var globalCount = 0;
var refCount = 0;
function startCountingUnrecognized() {
refCount++;
const start = globalCount;
return {
/**
* Ends counting and returns the delta.
* @param delta - If provided, only this amount is added to the parent counter
* (used for nested unions where we only want to record the winning option's count).
* If not provided, records all counts since start().
*/
end: (delta) => {
const count = globalCount - start;
globalCount = start + (delta ?? count);
if (--refCount === 0) globalCount = 0;
return count;
}
};
}
// ../sdk/src/types/default-to-zero-value.ts
var globalCount2 = 0;
var refCount2 = 0;
function defaultToZeroValue(value) {
globalCount2++;
return unrecognized(value);
}
function startCountingDefaultToZeroValue() {
refCount2++;
const start = globalCount2;
return {
/**
* Ends counting and returns the delta.
* @param delta - If provided, only this amount is added to the parent counter
* (used for nested unions where we only want to record the winning option's count).
* If not provided, records all counts since start().
*/
end: (delta) => {
const count = globalCount2 - start;
globalCount2 = start + (delta ?? count);
if (--refCount2 === 0) globalCount2 = 0;
return count;
}
};
}
// ../sdk/src/types/primitives.ts
function string4() {
return z6.union([
z6.string(),
// Null or undefined -> ""
zodDefaultToZeroValue(""),
// Any other value -> String(x)
z6.pipe(z6.any(), z6.transform((x) => unrecognized(JSON.stringify(x))))
]);
}
function boolean2() {
return z6.union([
z6.boolean(),
// String "true" (case insensitive) -> true, "false" -> false
z6.pipe(
z6.string(),
z6.transform((x, ctx) => {
const lower = x.toLowerCase();
if (lower === "true") return unrecognized(true);
if (lower === "false") return unrecognized(false);
ctx.issues.push({
input: x,
code: "invalid_type",
expected: "boolean",
received: "string"
});
return z6.NEVER;
})
),
zodDefaultToZeroValue(false)
]);
}
function number2() {
return z6.union([
z6.number(),
// String -> Number
z6.pipe(
z6.string(),
z6.transform((x, ctx) => {
const num = Number(x);
if (isNaN(num)) {
ctx.issues.push({
input: x,
code: "invalid_type",
expected: "number",
received: "string"
});
return z6.NEVER;
}
return unrecognized(num);
})
),
// Null or undefined -> 0
zodDefaultToZeroValue(0)
]);
}
function literal2(value) {
return z6.union([z6.literal(value), zodDefaultToZeroValue(value)]);
}
function optional3(t) {
return z6.optional(z6.union([
// Null -> undefined
z6.pipe(z6.null(), z6.transform(() => unrecognized(void 0))),
t
]));
}
function nullable(t) {
return z6.union([
z6.null(),
// Undefined -> null
z6.pipe(z6.undefined(), z6.transform(() => defaultToZeroValue(null))),
t
]);
}
function zodDefaultToZeroValue(value) {
return z6.pipe(
z6.any(),
z6.transform((input, ctx) => {
if (input === void 0) return defaultToZeroValue(value);
if (input === null) return defaultToZeroValue(value);
ctx.issues.push({
input,
code: "invalid_type",
expected: "undefined",
received: "unknown"
});
return z6.NEVER;
})
);
}
// ../sdk/src/types/smart-union.ts
var z7 = __toESM(require("zod/v4-mini"), 1);
// ../sdk/src/types/rfcdate.ts
var dateRE = /^\d{4}-\d{2}-\d{2}$/;
var RFCDate = class _RFCDate {
serialized;
/**
* Creates a new RFCDate instance using today's date.
*/
static today() {
return new _RFCDate(/* @__PURE__ */ new Date());
}
/**
* Creates a new RFCDate instance using the provided input.
* If a string is used then in must be in the format YYYY-MM-DD.
*
* @param date A Date object or a date string in YYYY-MM-DD format
* @example
* new RFCDate("2022-01-01")
* @example
* new RFCDate(new Date())
*/
constructor(date2) {
if (typeof date2 === "string" && !dateRE.test(date2)) {
throw new RangeError(
"RFCDate: date strings must be in the format YYYY-MM-DD: " + date2
);
}
const value = new Date(date2);
if (isNaN(+value)) {
throw new RangeError("RFCDate: invalid date provided: " + date2);
}
this.serialized = value.toISOString().slice(0, "YYYY-MM-DD".length);
if (!dateRE.test(this.serialized)) {
throw new TypeError(
`RFCDate: failed to build valid date with given value: ${date2} serialized to ${this.serialized}`
);
}
}
toJSON() {
return this.toString();
}
toString() {
return this.serialized;
}
};
// ../sdk/src/types/smart-union.ts
function smartUnion(options) {
return z7.pipe(
z7.unknown(),
z7.transform((input, ctx) => {
const candidates = [];
const errors = options.map(() => []);
const parentUnrecognizedCtr = startCountingUnrecognized();
const parentZeroDefaultCtr = startCountingDefaultToZeroValue();
for (const [i, option] of options.entries()) {
const unrecognizedCtr = startCountingUnrecognized();
const zeroDefaultCtr = startCountingDefaultToZeroValue();
const result = option.safeParse(input);
const inexactCount = unrecognizedCtr.end();
const zeroDefaultCount = zeroDefaultCtr.end();
if (result.success) {
candidates.push({
data: result.data,
inexactCount,
zeroDefaultCount,
fieldCount: -1
// We'll count this later if needed
});
continue;
}
errors[i].push(...result.error.issues);
}
if (candidates.length === 0) {
parentUnrecognizedCtr.end(0);
parentZeroDefaultCtr.end(0);
ctx.issues.push({
input,
code: "invalid_union",
errors
});
return z7.NEVER;
}
let best = candidates[0];
for (const candidate of candidates) {
if (candidates.length > 1) {
candidate.fieldCount = countFieldsRecursive(candidate.data);
}
best = better(candidate, best);
}
parentUnrecognizedCtr.end(best.inexactCount);
parentZeroDefaultCtr.end(best.zeroDefaultCount);
return best.data;
})
);
}
function better(a, b) {
const aIsExact = a.inexactCount === 0;
const bIsExact = b.inexactCount === 0;
if (aIsExact !== bIsExact) {
return aIsExact ? a : b;
}
const actualFieldCountA = a.fieldCount - a.zeroDefaultCount;
const actualFieldCountB = b.fieldCount - b.zeroDefaultCount;
if (actualFieldCountA !== actualFieldCountB) {
return actualFieldCountA > actualFieldCountB ? a : b;
}
return a.inexactCount < b.inexactCount ? a : b;
}
function countFieldsRecursive(parsed) {
let fieldCount = 0;
const queue = [parsed];
let index = 0;
while (index < queue.length) {
const value = queue[index++];
if (value === void 0) {
continue;
}
const type = typeof value;
if (value === null || type === "number" || type === "string" || type === "boolean" || type === "bigint" || value instanceof Date || value instanceof RFCDate) {
fieldCount++;
continue;
}
if (Array.isArray(value)) {
queue.push(...value);
continue;
}
if (type === "object") {
queue.push(...Object.values(value));
}
}
return fieldCount;
}
// ../sdk/src/models/aggregate-events-op.ts
var Range = {
TwentyFourh: "24h",
Sevend: "7d",
Thirtyd: "30d",
Ninetyd: "90d",
LastCycle: "last_cycle",
Onebc: "1bc",
Threebc: "3bc"
};
var BinSize = {
Day: "day",
Hour: "hour",
Week: "week",
Month: "month"
};
var AggregateEventsFeatureId$outboundSchema = smartUnion([z8.string(), z8.array(z8.string())]);
var Range$outboundSchema = z8.enum(Range);
var BinSize$outboundSchema = z8.enum(
BinSize
);
var AggregateEventsCustomRange$outboundSchema = z8.object({
start: z8.number(),
end: z8.number()
});
var EventsAggregateParams$outboundSchema = z8.pipe(
z8.object({
customerId: z8.optional(z8.string()),
entityId: z8.optional(z8.string()),
featureId: smartUnion([z8.string(), z8.array(z8.string())]),
groupBy: z8.optional(z8.string()),
range: z8.optional(Range$outboundSchema),
binSize: z8._default(BinSize$outboundSchema, "day"),
customRange: z8.optional(
z8.lazy(() => AggregateEventsCustomRange$outboundSchema)
),
filterBy: z8.optional(z8.record(z8.string(), z8.string())),
maxGroups: z8.optional(z8.int())
}),
z8.transform((v) => {
return remap(v, {
customerId: "customer_id",
entityId: "entity_id",
featureId: "feature_id",
groupBy: "group_by",
binSize: "bin_size",
customRange: "custom_range",
filterBy: "filter_by",
maxGroups: "max_groups"
});
})
);
var AggregateEventsList$inboundSchema = z8.pipe(
z8.object({
period: number2(),
values: z8.record(z8.string(), number2()),
grouped_values: optional3(
z8.record(z8.string(), z8.record(z8.string(), number2()))
)
}),
z8.transform((v) => {
return remap(v, {
"grouped_values": "groupedValues"
});
})
);
var Total$inboundSchema = z8.object({
count: number2(),
sum: number2()
});
var AggregateEventsResponse$inboundSchema = z8.object({
list: z8.array(z8.lazy(() => AggregateEventsList$inboundSchema)),
total: z8.record(z8.string(), z8.lazy(() => Total$inboundSchema))
});
// ../sdk/src/models/attach-op.ts
var z10 = __toESM(require("zod/v4-mini"), 1);
// ../sdk/src/types/enums.ts
var z9 = __toESM(require("zod/v4-mini"), 1);
function inboundSchema(enumObj) {
const options = Object.values(enumObj);
return z9.union([
...options.map((x) => z9.literal(x)),
z9.pipe(z9.string(), z9.transform((x) => unrecognized(x)))
]);
}
// ../sdk/src/models/attach-op.ts
var AttachPriceInterval = {
OneOff: "one_off",
Week: "week",
Month: "month",
Quarter: "quarter",
SemiAnnual: "semi_annual",
Year: "year"
};
var AttachItemResetInterval = {
OneOff: "one_off",
Minute: "minute",
Hour: "hour",
Day: "day",
Week: "week",
Month: "month",
Quarter: "quarter",
SemiAnnual: "semi_annual",
Year: "year"
};
var AttachItemTierBehavior = {
Graduated: "graduated",
Volume: "volume"
};
var AttachItemPriceInterval = {
OneOff: "one_off",
Week: "week",
Month: "month",
Quarter: "quarter",
SemiAnnual: "semi_annual",
Year: "year"
};
var AttachItemBillingMethod = {
Prepaid: "prepaid",
UsageBased: "usage_based"
};
var AttachItemOnIncrease = {
BillImmediately: "bill_immediately",
ProrateImmediately: "prorate_immediately",
ProrateNextCycle: "prorate_next_cycle",
BillNextCycle: "bill_next_cycle"
};
var AttachItemOnDecrease = {
Prorate: "prorate",
ProrateImmediately: "prorate_immediately",
ProrateNextCycle: "prorate_next_cycle",
None: "none",
NoProrations: "no_prorations"
};
var AttachItemExpiryDurationType = {
Month: "month",
Forever: "forever"
};
var AttachAddItemResetInterval = {
OneOff: "one_off",
Minute: "minute",
Hour: "hour",
Day: "day",
Week: "week",
Month: "month",
Quarter: "quarter",
SemiAnnual: "semi_annual",
Year: "year"
};
var AttachAddItemTierBehavior = {
Graduated: "graduated",
Volume: "volume"
};
var AttachAddItemPriceInterval = {
OneOff: "one_off",
Week: "week",
Month: "month",
Quarter: "quarter",
SemiAnnual: "semi_annual",
Year: "year"
};
var AttachAddItemBillingMethod = {
Prepaid: "prepaid",
UsageBased: "usage_based"
};
var AttachAddItemOnIncrease = {
BillImmediately: "bill_immediately",
ProrateImmediately: "prorate_immediately",
ProrateNextCycle: "prorate_next_cycle",
BillNextCycle: "bill_next_cycle"
};
var AttachAddItemOnDecrease = {
Prorate: "prorate",
ProrateImmediately: "prorate_immediately",
ProrateNextCycle: "prorate_next_cycle",
None: "none",
NoProrations: "no_prorations"
};
var AttachAddItemExpiryDurationType = {
Month: "month",
Forever: "forever"
};
var AttachRemoveItemBillingMethod = {
Prepaid: "prepaid",
UsageBased: "usage_based"
};
var AttachIntervalRemoveItemEnum2 = {
OneOff: "one_off",
Minute: "minute",
Hour: "hour",
Day: "day",
Week: "week",
Month: "month",
Quarter: "quarter",
SemiAnnual: "semi_annual",
Year: "year"
};
var AttachIntervalRemoveItemEnum1 = {
OneOff: "one_off",
Week: "week",
Month: "month",
Quarter: "quarter",
SemiAnnual: "semi_annual",
Year: "year"
};
var AttachDurationType = {
Day: "day",
Month: "month",
Year: "year"
};
var AttachOnEnd = {
Bill: "bill",
Revert: "revert"
};
var AttachPurchaseLimitInterval = {
Hour: "hour",
Day: "day",
Week: "week",
Month: "month"
};
var AttachLimitType = {
Absolute: "absolute",
UsagePercentage: "usage_percentage"
};
var AttachUsageLimitInterval = {
Day: "day",
Week: "week",
Month: "month",
Year: "year"
};
var AttachThresholdType = {
Usage: "usage",
UsagePercentage: "usage_percentage",
Remaining: "remaining",
RemainingPercentage: "remaining_percentage"
};
var AttachProrationBehavior = {
ProrateImmediately: "prorate_immediately",
None: "none"
};
var AttachRedirectMode = {
Always: "always",
IfRequired: "if_required",
Never: "never"
};
var AttachPlanSchedule = {
Immediate: "immediate",
EndOfCycle: "end_of_cycle"
};
var AttachCode = {
ThreedsRequired: "3ds_required",
PaymentMethodRequired: "payment_method_required",
PaymentFailed: "payment_failed",
PaymentProcessing: "payment_processing"
};
var AttachFeatureQuantity$outboundSchema = z10.pipe(
z10.object({
featureId: z10.string(),
quantity: z10.optional(z10.number()),
adjustable: z10.optional(z10.boolean())
}),
z10.transform((v) => {
return remap(v, {
featureId: "feature_id"
});
})
);
var AttachPriceInterval$outboundSchema = z10.enum(AttachPriceInterval);
var AttachBasePrice$outboundSchema = z10.pipe(
z10.object({
amount: z10.number(),
interval: AttachPriceInterval$outboundSchema,
intervalCount: z10.optional(z10.number())
}),
z10.transform((v) => {
return remap(v, {
intervalCount: "interval_count"
});
})
);
var AttachItemResetInterval$outboundSchema = z10.enum(AttachItemResetInterval);
var AttachItemReset$outboundSchema = z10.pipe(
z10.object({
interval: AttachItemResetInterval$outboundSchema,
intervalCount: z10.optional(z10.number())
}),
z10.transform((v) => {
return remap(v, {
intervalCount: "interval_count"
});
})
);
var AttachItemTo$outboundSchema = smartUnion([z10.number(), z10.string()]);
var AttachItemTier$outboundSchema = z10.pipe(
z10.object({
to: smartUnion([z10.number(), z10.string()]),
amount: z10.optional(z10.number()),
flatAmount: z10.optional(z10.number())
}),
z10.transform((v) => {
return remap(v, {
flatAmount: "flat_amount"
});
})
);
var AttachItemTierBehavior$outboundSchema = z10.enum(AttachItemTierBehavior);
var AttachItemPriceInterval$outboundSchema = z10.enum(AttachItemPriceInterval);
var AttachItemBillingMethod$outboundSchema = z10.enum(AttachItemBillingMethod);
var AttachItemPrice$outboundSchema = z10.pipe(
z10.object({
amount: z10.optional(z10.number()),
tiers: z10.optional(z10.array(z10.lazy(() => AttachItemTier$outboundSchema))),
tierBehavior: z10.optional(AttachItemTierBehavior$outboundSchema),
interval: AttachItemPriceInterval$outboundSchema,
intervalCount: z10._default(z10.number(), 1),
billingUnits: z10._default(z10.number(), 1),
billingMethod: AttachItemBillingMethod$outboundSchema,
maxPurchase: z10.optional(z10.nullable(z10.number()))
}),
z10.transform((v) => {
return remap(v, {
tierBehavior: "tier_behavior",
intervalCount: "interval_count",
billingUnits: "billing_units",
billingMethod: "billing_method",
maxPurchase: "max_purchase"
});
})
);
var AttachItemOnIncrease$outboundSchema = z10.enum(AttachItemOnIncrease);
var AttachItemOnDecrease$outboundSchema = z10.enum(AttachItemOnDecrease);
var AttachItemProration$outboundSchema = z10.pipe(
z10.object({
onIncrease: AttachItemOnIncrease$outboundSchema,
onDecrease: AttachItemOnDecrease$outboundSchema
}),
z10.transform((v) => {
return remap(v, {
onIncrease: "on_increase",
onDecrease: "on_decrease"
});
})
);
var AttachItemExpiryDurationType$outboundSchema = z10.enum(AttachItemExpiryDurationType);
var AttachItemRollover$outboundSchema = z10.pipe(
z10.object({
max: z10.optional(z10.number()),
maxPercentage: z10.optional(z10.number()),
expiryDurationType: AttachItemExpiryDurationType$outboundSchema,
expiryDurationLength: z10.optional(z10.number())
}),
z10.transform((v) => {
return remap(v, {
maxPercentage: "max_percentage",
expiryDurationType: "expiry_duration_type",
expiryDurationLength: "expiry_duration_length"
});
})
);
var AttachItemPlanItem$outboundSchema = z10.pipe(
z10.object({
featureId: z10.string(),
included: z10.optional(z10.number()),
unlimited: z10.optional(z10.boolean()),
reset: z10.optional(z10.lazy(() => AttachItemReset$outboundSchema)),
price: z10.optional(z10.lazy(() => AttachItemPrice$outboundSchema)),
proration: z10.optional(z10.lazy(() => AttachItemProration$outboundSchema)),
rollover: z10.optional(z10.lazy(() => AttachItemRollover$outboundSchema))
}),
z10.transform((v) => {
return remap(v, {
featureId: "feature_id"
});
})
);
var AttachAddItemResetInterval$outboundSchema = z10.enum(AttachAddItemResetInterval);
var AttachAddItemReset$outboundSchema = z10.pipe(
z10.object({
interval: AttachAddItemResetInterval$outboundSchema,
intervalCount: z10.optional(z10.number())
}),
z10.transform((v) => {
return remap(v, {
intervalCount: "interval_count"
});
})
);
var AttachAddItemTo$outboundSchema = smartUnion([z10.number(), z10.string()]);
var AttachAddItemTier$outboundSchema = z10.pipe(
z10.object({
to: smartUnion([z10.number(), z10.string()]),
amount: z10.optional(z10.number()),
flatAmount: z10.optional(z10.number())
}),
z10.transform((v) => {
return remap(v, {
flatAmount: "flat_amount"
});
})
);
var AttachAddItemTierBehavior$outboundSchema = z10.enum(AttachAddItemTierBehavior);
var AttachAddItemPriceInterval$outboundSchema = z10.enum(AttachAddItemPriceInterval);
var AttachAddItemBillingMethod$outboundSchema = z10.enum(AttachAddItemBillingMethod);
var AttachAddItemPrice$outboundSchema = z10.pipe(
z10.object({
amount: z10.optional(z10.number()),
tiers: z10.optional(z10.array(z10.lazy(() => AttachAddItemTier$outboundSchema))),
tierBehavior: z10.optional(AttachAddItemTierBehavior$outboundSchema),
interval: AttachAddItemPriceInterval$outboundSchema,
intervalCount: z10._default(z10.number(), 1),
billingUnits: z10._default(z10.number(), 1),
billingMethod: AttachAddItemBillingMethod$outboundSchema,
maxPurchase: z10.optional(z10.nullable(z10.number()))
}),
z10.transform((v) => {
return remap(v, {
tierBehavior: "tier_behavior",
intervalCount: "interval_count",
billingUnits: "billing_units",
billingMethod: "billing_method",
maxPurchase: "max_purchase"
});
})
);
var AttachAddItemOnIncrease$outboundSchema = z10.enum(AttachAddItemOnIncrease);
var AttachAddItemOnDecrease$outboundSchema = z10.enum(AttachAddItemOnDecrease);
var AttachAddItemProration$outboundSchema = z10.pipe(
z10.object({
onIncrease: AttachAddItemOnInc