ts / dist / cjs / jobs.js
811 words
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.run = exports.userMessage = exports.imagePart = exports.textPart = exports.nlpDetectLanguage = exports.nlpAnalyze = exports.llmRawCompletion = exports.llmChat = exports.embedding = exports.domainAvailabilityBulk = exports.getResult = exports.get = exports.enqueue = void 0;
const errors_js_1 = require("./errors.js");
const http = __importStar(require("./http.js"));
/** POST /jobs — Enqueue a job (202 with the queued job). */
const enqueue = (client, spec) => http.post(client, '/jobs', { body: spec });
exports.enqueue = enqueue;
/** GET /jobs/{id} — Job status: queued/processing/succeeded/failed. */
const get = (client, id) => http.get(client, '/jobs/{id}', { params: { id } });
exports.get = get;
/** GET /jobs/{id}/result — Job result. 409 while still running, 410 once expired (24h). */
const getResult = (client, id) => http.get(client, '/jobs/{id}/result', { params: { id } });
exports.getResult = getResult;
// ---------------------------------------------------------------------------
// Payload builders (one per job type). Options merge first, so `type` and
// the primary input can never be overridden.
/** Check up to 100 domains in one job. */
const domainAvailabilityBulk = (domains) => ({
    type: 'domain-availability-bulk',
    domains: [...domains],
});
exports.domainAvailabilityBulk = domainAvailabilityBulk;
/** Embed INPUT text (`model` defaults server-side). */
const embedding = (input, options = {}) => ({
    ...options,
    type: 'embedding',
    input,
});
exports.embedding = embedding;
/** Chat completion over MESSAGES. */
const llmChat = (messages, options = {}) => ({ ...options, type: 'llm-chat', messages: [...messages] });
exports.llmChat = llmChat;
/** Raw completion of PROMPT. */
const llmRawCompletion = (prompt, options = {}) => ({ ...options, type: 'llm-raw-completion', prompt });
exports.llmRawCompletion = llmRawCompletion;
/** NLP analysis of INPUT text. */
const nlpAnalyze = (input, options = {}) => ({
    ...options,
    type: 'nlp-analyze',
    input,
});
exports.nlpAnalyze = nlpAnalyze;
/** Language detection of INPUT text. */
const nlpDetectLanguage = (input) => ({
    type: 'nlp-detect-language',
    input,
});
exports.nlpDetectLanguage = nlpDetectLanguage;
const MIME_TYPES = {
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.jpeg': 'image/jpeg',
    '.webp': 'image/webp',
    '.gif': 'image/gif',
};
const guessMime = (path) => {
    const lower = path.toLowerCase();
    return Object.entries(MIME_TYPES).find(([ext]) => lower.endsWith(ext))?.[1];
};
const toBase64 = (bytes) => {
    let binary = '';
    for (let i = 0; i < bytes.length; i += 0x8000) {
        binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
    }
    return btoa(binary);
};
/** OpenAI-style text content part. */
const textPart = (text) => ({ type: 'text', text });
exports.textPart = textPart;
/**
 * OpenAI-style image_url content part from SOURCE (a file path or bytes),
 * embedded as a base64 data URL. The MIME type is sniffed from a path's
 * extension (png/jpg/jpeg/webp/gif) or passed explicitly.
 */
const imagePart = async (source, mimeType) => {
    const mime = mimeType ?? (typeof source === 'string' ? guessMime(source) : undefined);
    if (!mime)
        throw (0, errors_js_1.configError)('Cannot guess image MIME type; pass it explicitly', { source });
    const bytes = typeof source === 'string' ? new Uint8Array(await (await Promise.resolve().then(() => __importStar(require('node:fs/promises')))).readFile(source)) : source;
    return { type: 'image_url', image_url: { url: `data:${mime};base64,${toBase64(bytes)}` } };
};
exports.imagePart = imagePart;
/** A user message whose content is TEXT plus any IMAGE-PARTS (from `imagePart`). */
const userMessage = (text, ...imageParts) => ({
    role: 'user',
    content: [(0, exports.textPart)(text), ...imageParts],
});
exports.userMessage = userMessage;
const TERMINAL = new Set(['succeeded', 'failed']);
/**
 * Enqueue SPEC, poll until the job reaches a terminal status, then fetch
 * and return the result. Throws a jobFailed error with the failed job, or a
 * timeout error when the deadline passes first.
 */
const run = async (client, spec, options = {}) => {
    const { job } = await (0, exports.enqueue)(client, spec);
    const id = job.id;
    const { job: final } = await http.pollUntil(() => (0, exports.get)(client, id), (r) => TERMINAL.has(r.job.status), {
        intervalMs: options.intervalMs,
        timeoutMs: options.timeoutMs ?? 120000,
        message: `Timed out waiting for job ${id}`,
        sleep: client.sleep,
    });
    if (final.status === 'succeeded')
        return (0, exports.getResult)(client, id);
    throw (0, errors_js_1.jobFailed)(`Job ${id} failed`, final);
};
exports.run = run;

static mirror of HEAD · about · clone: git clone https://ird.cod-sursa.ro/ts.git