@docmana/sdk 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/LICENSE +21 -0
- package/README.md +307 -0
- package/dist/cli.mjs +772 -0
- package/dist/cli.mjs.map +1 -0
- package/dist/index.d.cts +107 -0
- package/dist/index.d.ts +107 -0
- package/dist/index.js +449 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +414 -0
- package/dist/index.mjs.map +1 -0
- package/dist/package.json +1 -0
- package/package.json +64 -0
package/dist/cli.mjs.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts","../src/errors.ts","../src/auth/token-manager.ts","../src/config.ts","../src/http/http-client.ts","../src/files/resolve-input.ts","../src/api/upload.ts","../src/api/run-flow.ts","../src/api/execution-status.ts","../src/api/execution-result.ts","../src/polling/poll.ts","../src/client.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { mkdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\nimport { createInterface } from \"node:readline/promises\";\nimport { fileURLToPath } from \"node:url\";\nimport { Command, CommanderError } from \"commander\";\nimport { TokenManager } from \"./auth/token-manager.js\";\nimport { Docmana } from \"./client.js\";\nimport { DEFAULTS } from \"./config.js\";\nimport { DocmanaError, DocmanaExecutionError } from \"./errors.js\";\nimport type { DocmanaConfig, ExecutionResult, RunFlowInput, TokenCache } from \"./types.js\";\n\ntype Env = Record<string, string | undefined>;\ntype Write = (text: string) => void;\n\nexport interface CliIO {\n stdout: Write;\n stderr: Write;\n}\n\nexport interface DocmanaClient {\n runFlow(flowId: string, input: RunFlowInput): Promise<ExecutionResult>;\n}\n\nexport type DocmanaClientFactory = (config: DocmanaConfig) => DocmanaClient;\n\nexport interface DocmanaCliConfig {\n apiBaseUrl?: string;\n tokenEndpoint?: string;\n scope?: string;\n organisation?: string;\n clientId?: string;\n clientSecret?: string;\n}\n\ninterface CliPromptOptions {\n defaultValue?: string;\n secret?: boolean;\n}\n\nexport type CliPrompt = (label: string, options?: CliPromptOptions) => Promise<string>;\n\nexport interface CliDeps {\n cwd?: string;\n prompt?: CliPrompt;\n fetch?: typeof fetch;\n}\n\nclass CliUsageError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CliUsageError\";\n }\n}\n\ninterface RunOptions {\n files?: string;\n clientId?: string;\n clientSecret?: string;\n apiUrl?: string;\n tokenUrl?: string;\n scope?: string;\n organisation?: string;\n config?: string;\n tokenCache?: string;\n json?: boolean;\n}\n\ninterface ConfigInitOptions {\n config?: string;\n}\n\ninterface LoginOptions {\n clientId?: string;\n clientSecret?: string;\n tokenUrl?: string;\n scope?: string;\n config?: string;\n tokenCache?: string;\n}\n\nconst HELP = {\n root: \"Run Docmana document-analysis flows.\",\n flow: \"Manage and run Docmana flows.\",\n config: \"Manage Docmana CLI configuration.\",\n configInit: \"Create or update a local Docmana CLI config file.\",\n login: \"Acquire and cache a Docmana OAuth2 access token.\",\n run: \"Upload documents, run a Docmana flow, wait for completion, and print the result.\",\n};\n\nconst DEFAULT_CONFIG_FILE = \"docmana.config.json\";\nconst DEFAULT_TOKEN_CACHE_FILE = \"docmana.token.json\";\n\nexport async function runCli(\n argv: string[] = process.argv.slice(2),\n env: Env = process.env,\n io: CliIO = {\n stdout: (text) => process.stdout.write(text),\n stderr: (text) => process.stderr.write(text),\n },\n clientFactory: DocmanaClientFactory = (config) => new Docmana(config),\n deps: CliDeps = {},\n): Promise<number> {\n const program = buildProgram(env, io, clientFactory, deps);\n if (argv.length === 0) {\n io.stdout(program.helpInformation());\n return 0;\n }\n\n try {\n await program.parseAsync(argv, { from: \"user\" });\n return 0;\n } catch (err) {\n if (err instanceof CliUsageError) {\n io.stderr(`Error: ${err.message}\\n`);\n return 2;\n }\n if (err instanceof CommanderError) {\n return err.exitCode === 0 ? 0 : 2;\n }\n io.stderr(`${formatRuntimeError(err)}\\n`);\n return 1;\n }\n}\n\nfunction buildProgram(\n env: Env,\n io: CliIO,\n clientFactory: DocmanaClientFactory,\n deps: CliDeps,\n): Command {\n const program = new Command();\n program\n .name(\"docmana\")\n .description(HELP.root)\n .showHelpAfterError()\n .configureOutput({\n writeOut: io.stdout,\n writeErr: io.stderr,\n outputError: (str, write) => write(str),\n })\n .exitOverride();\n\n program\n .command(\"login\")\n .description(HELP.login)\n .option(\"--client-id <id>\", \"OAuth2 client id; defaults to DOCMANA_CLIENT_ID\")\n .option(\"--client-secret <secret>\", \"OAuth2 client secret; defaults to DOCMANA_CLIENT_SECRET\")\n .option(\"--token-url <url>\", \"OAuth2 token endpoint; defaults to DOCMANA_TOKEN_URL\")\n .option(\"--scope <scope>\", \"OAuth2 scope; defaults to DOCMANA_SCOPE\")\n .option(\"--config <path>\", `Config file path; defaults to ./${DEFAULT_CONFIG_FILE}`)\n .option(\"--token-cache <path>\", `Token cache path; defaults to ./${DEFAULT_TOKEN_CACHE_FILE}`)\n .action(async (options: LoginOptions) => {\n await loginCommand(options, env, io, deps);\n });\n\n const flow = program\n .command(\"flow\")\n .description(HELP.flow)\n .action(() => {\n io.stdout(flow.helpInformation());\n });\n\n flow\n .command(\"run\")\n .description(HELP.run)\n .argument(\"<flow-id>\", \"Docmana flow id\")\n .requiredOption(\"--files <csv>\", \"Comma-separated file paths to upload\")\n .option(\"--client-id <id>\", \"OAuth2 client id; defaults to DOCMANA_CLIENT_ID\")\n .option(\"--client-secret <secret>\", \"OAuth2 client secret; defaults to DOCMANA_CLIENT_SECRET\")\n .option(\"--api-url <url>\", \"Docmana API base URL; defaults to DOCMANA_API_URL\")\n .option(\"--token-url <url>\", \"OAuth2 token endpoint; defaults to DOCMANA_TOKEN_URL\")\n .option(\"--scope <scope>\", \"OAuth2 scope; defaults to DOCMANA_SCOPE\")\n .option(\"--organisation <id>\", \"Docmana organisation id; defaults to DOCMANA_ORGANISATION\")\n .option(\"--config <path>\", `Config file path; defaults to ./${DEFAULT_CONFIG_FILE}`)\n .option(\"--token-cache <path>\", `Token cache path; defaults to ./${DEFAULT_TOKEN_CACHE_FILE}`)\n .option(\"--json\", \"Print the raw JSON result\")\n .action(async (flowId: string, options: RunOptions) => {\n await runFlowCommand(flowId, options, env, io, clientFactory, deps);\n });\n\n const config = program\n .command(\"config\")\n .description(HELP.config)\n .action(() => {\n io.stdout(config.helpInformation());\n });\n\n config\n .command(\"init\")\n .description(HELP.configInit)\n .option(\"--config <path>\", `Config file path; defaults to ./${DEFAULT_CONFIG_FILE}`)\n .action(async (options: ConfigInitOptions) => {\n await configInitCommand(options, io, deps);\n });\n\n return program;\n}\n\nasync function runFlowCommand(\n flowId: string,\n options: RunOptions,\n env: Env,\n io: CliIO,\n clientFactory: DocmanaClientFactory,\n deps: CliDeps,\n): Promise<void> {\n const files = parseFiles(options.files);\n const cliConfig = await loadCliConfig(options.config, getCwd(deps), Boolean(options.config));\n const clientId = firstNonEmpty(options.clientId, env.DOCMANA_CLIENT_ID, cliConfig.clientId);\n const clientSecret = firstNonEmpty(\n options.clientSecret,\n env.DOCMANA_CLIENT_SECRET,\n cliConfig.clientSecret,\n );\n const organisation = firstNonEmpty(\n options.organisation,\n env.DOCMANA_ORGANISATION,\n cliConfig.organisation,\n );\n const apiBaseUrl = firstNonEmpty(options.apiUrl, env.DOCMANA_API_URL, cliConfig.apiBaseUrl);\n const tokenEndpoint = firstNonEmpty(\n options.tokenUrl,\n env.DOCMANA_TOKEN_URL,\n cliConfig.tokenEndpoint,\n );\n const scope = firstNonEmpty(options.scope, env.DOCMANA_SCOPE, cliConfig.scope);\n\n if (!clientId)\n throw new CliUsageError(\"Missing client id. Use --client-id or DOCMANA_CLIENT_ID.\");\n if (!clientSecret) {\n throw new CliUsageError(\"Missing client secret. Use --client-secret or DOCMANA_CLIENT_SECRET.\");\n }\n if (!organisation) {\n throw new CliUsageError(\"Missing organisation. Use --organisation or DOCMANA_ORGANISATION.\");\n }\n\n const client = clientFactory({\n clientId,\n clientSecret,\n apiBaseUrl,\n tokenEndpoint,\n scope,\n headers: { \"X-Selected-Organization\": organisation },\n tokenCache: createFileTokenCache(resolveTokenCachePath(options.tokenCache, getCwd(deps))),\n });\n const result = await client.runFlow(flowId, { files: files.map((path) => ({ path })) });\n\n if (options.json) {\n io.stdout(`${JSON.stringify(result, null, 2)}\\n`);\n return;\n }\n io.stdout(formatHumanResult(result));\n}\n\nasync function loginCommand(\n options: LoginOptions,\n env: Env,\n io: CliIO,\n deps: CliDeps,\n): Promise<void> {\n const auth = await resolveAuthConfig(options, env, deps);\n const tokenCachePath = resolveTokenCachePath(options.tokenCache, getCwd(deps));\n const tokenCache = createFileTokenCache(tokenCachePath);\n const tokenManager = new TokenManager({\n clientId: auth.clientId,\n clientSecret: auth.clientSecret,\n tokenEndpoint: auth.tokenEndpoint,\n scope: auth.scope,\n fetchImpl: deps.fetch ?? fetch,\n tokenCache,\n });\n\n await tokenManager.getToken();\n const cached = await tokenCache.read();\n io.stdout(`Logged in. Token cached at ${tokenCachePath}\\n`);\n if (cached) io.stdout(formatTokenExpiry(cached.expiresAt));\n}\n\nfunction formatTokenExpiry(expiresAt: number): string {\n const expiresAtDate = new Date(expiresAt);\n return (\n [\n `Token expires at local time ${expiresAtDate.toLocaleString()}`,\n `Token expires at UTC ${expiresAtDate.toISOString()}`,\n ].join(\"\\n\") + \"\\n\"\n );\n}\n\nasync function resolveAuthConfig(\n options: LoginOptions,\n env: Env,\n deps: CliDeps,\n): Promise<{ clientId: string; clientSecret: string; tokenEndpoint: string; scope: string }> {\n const cliConfig = await loadCliConfig(options.config, getCwd(deps), Boolean(options.config));\n const clientId = firstNonEmpty(options.clientId, env.DOCMANA_CLIENT_ID, cliConfig.clientId);\n const clientSecret = firstNonEmpty(\n options.clientSecret,\n env.DOCMANA_CLIENT_SECRET,\n cliConfig.clientSecret,\n );\n const tokenEndpoint =\n firstNonEmpty(options.tokenUrl, env.DOCMANA_TOKEN_URL, cliConfig.tokenEndpoint) ??\n DEFAULTS.tokenEndpoint;\n const scope = firstNonEmpty(options.scope, env.DOCMANA_SCOPE, cliConfig.scope) ?? DEFAULTS.scope;\n\n if (!clientId)\n throw new CliUsageError(\"Missing client id. Use --client-id or DOCMANA_CLIENT_ID.\");\n if (!clientSecret) {\n throw new CliUsageError(\"Missing client secret. Use --client-secret or DOCMANA_CLIENT_SECRET.\");\n }\n\n return { clientId, clientSecret, tokenEndpoint, scope };\n}\n\nasync function configInitCommand(\n options: ConfigInitOptions,\n io: CliIO,\n deps: CliDeps,\n): Promise<void> {\n const cwd = getCwd(deps);\n const configPath = resolveConfigPath(options.config, cwd);\n const existing = await loadCliConfig(options.config, cwd, false);\n const defaultPrompt = deps.prompt ? undefined : createDefaultPrompt();\n const prompt = deps.prompt ?? defaultPrompt?.prompt;\n if (!prompt) throw new CliUsageError(\"Unable to initialize interactive prompt\");\n\n try {\n const config: DocmanaCliConfig = {\n apiBaseUrl: await prompt(\"API base URL\", {\n defaultValue: existing.apiBaseUrl ?? DEFAULTS.apiBaseUrl,\n }),\n tokenEndpoint: await prompt(\"OAuth2 token endpoint\", {\n defaultValue: existing.tokenEndpoint ?? DEFAULTS.tokenEndpoint,\n }),\n scope: await prompt(\"OAuth2 scope\", {\n defaultValue: existing.scope ?? DEFAULTS.scope,\n }),\n organisation: await prompt(\"Organisation\", {\n defaultValue: existing.organisation,\n }),\n clientId: await prompt(\"Client id\", {\n defaultValue: existing.clientId,\n }),\n clientSecret: await prompt(\"Client secret\", {\n defaultValue: existing.clientSecret,\n secret: true,\n }),\n };\n\n await mkdir(dirname(configPath), { recursive: true });\n await writeFile(configPath, `${JSON.stringify(config, null, 2)}\\n`, \"utf8\");\n io.stdout(`Wrote ${configPath}\\n`);\n io.stdout(\n `Warning: ${DEFAULT_CONFIG_FILE} contains credentials and should stay ignored by Git.\\n`,\n );\n } finally {\n defaultPrompt?.close();\n }\n}\n\nasync function loadCliConfig(\n configPathOption: string | undefined,\n cwd: string,\n requireExisting: boolean,\n): Promise<DocmanaCliConfig> {\n const configPath = resolveConfigPath(configPathOption, cwd);\n if (!existsSync(configPath)) {\n if (requireExisting) throw new CliUsageError(`Config file not found: ${configPath}`);\n return {};\n }\n let raw: string;\n try {\n raw = await readFile(configPath, \"utf8\");\n } catch {\n throw new CliUsageError(`Unable to read config file: ${configPath}`);\n }\n try {\n const parsed = JSON.parse(raw) as unknown;\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new Error(\"Config must be a JSON object\");\n }\n return normalizeCliConfig(parsed as Record<string, unknown>);\n } catch {\n throw new CliUsageError(`Invalid config file: ${configPath}`);\n }\n}\n\nfunction normalizeCliConfig(config: Record<string, unknown>): DocmanaCliConfig {\n return {\n apiBaseUrl: stringValue(config.apiBaseUrl),\n tokenEndpoint: stringValue(config.tokenEndpoint),\n scope: stringValue(config.scope),\n organisation: stringValue(config.organisation),\n clientId: stringValue(config.clientId),\n clientSecret: stringValue(config.clientSecret),\n };\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim() ? value : undefined;\n}\n\nfunction resolveConfigPath(configPathOption: string | undefined, cwd: string): string {\n return resolve(cwd, configPathOption ?? DEFAULT_CONFIG_FILE);\n}\n\nfunction resolveTokenCachePath(tokenCachePathOption: string | undefined, cwd: string): string {\n return resolve(cwd, tokenCachePathOption ?? DEFAULT_TOKEN_CACHE_FILE);\n}\n\nfunction getCwd(deps: CliDeps): string {\n return deps.cwd ?? process.cwd();\n}\n\nfunction createFileTokenCache(path: string): TokenCache {\n return {\n async read() {\n if (!existsSync(path)) return null;\n try {\n const parsed = JSON.parse(await readFile(path, \"utf8\")) as unknown;\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return null;\n const value = parsed as Record<string, unknown>;\n if (\n typeof value.accessToken !== \"string\" ||\n typeof value.expiresAt !== \"number\" ||\n typeof value.clientId !== \"string\" ||\n typeof value.tokenEndpoint !== \"string\" ||\n typeof value.scope !== \"string\"\n ) {\n return null;\n }\n return {\n accessToken: value.accessToken,\n expiresAt: value.expiresAt,\n clientId: value.clientId,\n tokenEndpoint: value.tokenEndpoint,\n scope: value.scope,\n };\n } catch {\n return null;\n }\n },\n async write(entry) {\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, `${JSON.stringify(entry, null, 2)}\\n`, \"utf8\");\n },\n async clear() {\n await rm(path, { force: true });\n },\n };\n}\n\nfunction createDefaultPrompt(): { prompt: CliPrompt; close: () => void } {\n if (!process.stdin.isTTY) {\n let index = 0;\n const linesPromise = readStdinLines();\n return {\n prompt: async (label, options = {}) => {\n process.stdout.write(formatPrompt(label, options));\n const lines = await linesPromise;\n const answer = lines[index++] ?? \"\";\n return firstNonEmpty(answer, options.defaultValue) ?? \"\";\n },\n close: () => undefined,\n };\n }\n\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n return {\n prompt: async (label, options = {}) => {\n const answer = await rl.question(formatPrompt(label, options));\n return firstNonEmpty(answer, options.defaultValue) ?? \"\";\n },\n close: () => rl.close(),\n };\n}\n\nfunction formatPrompt(label: string, options: CliPromptOptions): string {\n const defaultHint =\n options.defaultValue && !options.secret\n ? ` [${options.defaultValue}]`\n : options.defaultValue && options.secret\n ? \" [current value hidden]\"\n : \"\";\n return `${label}${defaultHint}: `;\n}\n\nasync function readStdinLines(): Promise<string[]> {\n let input = \"\";\n for await (const chunk of process.stdin) input += String(chunk);\n return input.split(/\\r?\\n/);\n}\n\nfunction parseFiles(filesCsv: string | undefined): string[] {\n const files =\n filesCsv\n ?.split(\",\")\n .map((file) => file.trim())\n .filter(Boolean) ?? [];\n if (files.length === 0) throw new CliUsageError(\"Missing files. Use --files <path[,path]>.\");\n return files;\n}\n\nfunction firstNonEmpty(...values: Array<string | undefined>): string | undefined {\n return values.map((value) => value?.trim()).find(Boolean);\n}\n\nfunction formatHumanResult(result: ExecutionResult): string {\n const lines = [\"Docmana flow completed\", `Status: ${String(result.status ?? \"Unknown\")}`];\n const executionId = result.execution_id ?? result.executionResultId ?? result.execution_result_id;\n if (executionId) lines.push(`Execution id: ${String(executionId)}`);\n if (Array.isArray(result.results)) lines.push(`Results: ${result.results.length}`);\n if (Array.isArray(result.errors)) lines.push(`Errors: ${result.errors.length}`);\n const preview = formatResultsPreview(result.results);\n if (preview) lines.push(\"\", \"Result preview:\", preview);\n lines.push(\"\", \"Use --json to print the complete result payload.\");\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction formatResultsPreview(results: unknown): string | undefined {\n if (!Array.isArray(results) || results.length === 0) return undefined;\n const preview = JSON.stringify(results.slice(0, 3), null, 2);\n if (!preview) return undefined;\n return preview.length > 2_000 ? `${preview.slice(0, 2_000)}\\n...` : preview;\n}\n\nfunction formatRuntimeError(err: unknown): string {\n if (err instanceof DocmanaExecutionError) {\n const details = err.errors.length > 0 ? ` (${err.errors.length} error(s))` : \"\";\n return `${err.message}${details}`;\n }\n if (err instanceof DocmanaError) return err.message;\n if (err instanceof Error) return err.message;\n return \"Unexpected error\";\n}\n\nfunction isDirectRun(): boolean {\n const entry = process.argv[1];\n if (!entry) return false;\n try {\n return realpathSync(resolve(entry)) === realpathSync(fileURLToPath(import.meta.url));\n } catch {\n return false;\n }\n}\n\nif (isDirectRun()) {\n runCli().then((code) => {\n process.exitCode = code;\n });\n}\n","export class DocmanaError extends Error {\n readonly status?: number;\n readonly requestId?: string;\n readonly code: string;\n constructor(message: string, opts: { status?: number; requestId?: string; code?: string } = {}) {\n super(message);\n this.name = new.target.name;\n this.status = opts.status;\n this.requestId = opts.requestId;\n this.code = opts.code ?? \"docmana_error\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class DocmanaAuthError extends DocmanaError {\n constructor(message: string, opts: { status?: number; requestId?: string } = {}) {\n super(message, { ...opts, code: \"auth_error\" });\n }\n}\n\nexport class DocmanaPermissionError extends DocmanaError {\n constructor(message: string, opts: { status?: number; requestId?: string } = {}) {\n super(message, { ...opts, code: \"permission_error\" });\n }\n}\n\nexport class DocmanaNotFoundError extends DocmanaError {\n constructor(message: string, opts: { status?: number; requestId?: string } = {}) {\n super(message, { ...opts, code: \"not_found\" });\n }\n}\n\nexport class DocmanaRequestError extends DocmanaError {\n constructor(message: string, opts: { status?: number; requestId?: string } = {}) {\n super(message, { ...opts, code: \"bad_request\" });\n }\n}\n\nexport class DocmanaExecutionError extends DocmanaError {\n readonly errors: unknown[];\n constructor(message: string, errors: unknown[] = []) {\n super(message, { code: \"execution_failed\" });\n this.errors = errors;\n }\n}\n\nexport class DocmanaTimeoutError extends DocmanaError {\n constructor(message: string) {\n super(message, { code: \"timeout\" });\n }\n}\n\nexport class DocmanaAbortError extends DocmanaError {\n constructor(message: string) {\n super(message, { code: \"aborted\" });\n }\n}\n\nexport function errorFromResponse(\n status: number,\n message: string,\n requestId?: string,\n): DocmanaError {\n const opts = { status, requestId };\n switch (status) {\n case 400:\n return new DocmanaRequestError(message, opts);\n case 401:\n return new DocmanaAuthError(message, opts);\n case 403:\n return new DocmanaPermissionError(message, opts);\n case 404:\n return new DocmanaNotFoundError(message, opts);\n default:\n return new DocmanaError(message, opts);\n }\n}\n","import { DocmanaAuthError } from \"../errors.js\";\nimport type { TokenCache, TokenCacheEntry } from \"../types.js\";\n\nconst SAFETY_MARGIN_MS = 60_000;\n\nexport interface TokenManagerOptions {\n clientId: string;\n clientSecret: string;\n tokenEndpoint: string;\n scope: string;\n fetchImpl: typeof fetch;\n tokenCache?: TokenCache;\n}\n\nexport class TokenManager {\n private token: string | null = null;\n private expiresAt = 0;\n private inflight: Promise<string> | null = null;\n\n constructor(private readonly opts: TokenManagerOptions) {}\n\n invalidate(): void {\n this.token = null;\n this.expiresAt = 0;\n void this.opts.tokenCache?.clear().catch(() => undefined);\n }\n\n async getToken(): Promise<string> {\n if (this.token && Date.now() < this.expiresAt) return this.token;\n const cached = await this.readCachedToken();\n if (cached) return cached;\n if (this.inflight) return this.inflight;\n this.inflight = this.acquire().finally(() => {\n this.inflight = null;\n });\n return this.inflight;\n }\n\n private async acquire(): Promise<string> {\n const body = new URLSearchParams({\n grant_type: \"client_credentials\",\n client_id: this.opts.clientId,\n client_secret: this.opts.clientSecret,\n scope: this.opts.scope,\n });\n const res = await this.opts.fetchImpl(this.opts.tokenEndpoint, {\n method: \"POST\",\n headers: { \"content-type\": \"application/x-www-form-urlencoded\" },\n body: body.toString(),\n });\n if (!res.ok) {\n // Do NOT include the response body verbatim — avoid leaking secrets/echoes.\n throw new DocmanaAuthError(\"Failed to acquire Docmana access token\", { status: res.status });\n }\n const json = (await res.json()) as Partial<{ access_token: string; expires_in: number }>;\n if (\n typeof json.access_token !== \"string\" ||\n json.access_token.length === 0 ||\n typeof json.expires_in !== \"number\" ||\n !Number.isFinite(json.expires_in)\n ) {\n throw new DocmanaAuthError(\"Malformed token response from Docmana CIAM\", {\n status: res.status,\n });\n }\n this.token = json.access_token;\n this.expiresAt = Date.now() + json.expires_in * 1000 - SAFETY_MARGIN_MS;\n await this.writeCachedToken().catch(() => undefined);\n return this.token;\n }\n\n private async readCachedToken(): Promise<string | null> {\n if (!this.opts.tokenCache) return null;\n let entry: TokenCacheEntry | null;\n try {\n entry = await this.opts.tokenCache.read();\n } catch {\n return null;\n }\n if (!entry) return null;\n if (\n entry.clientId !== this.opts.clientId ||\n entry.tokenEndpoint !== this.opts.tokenEndpoint ||\n entry.scope !== this.opts.scope ||\n Date.now() >= entry.expiresAt\n ) {\n await this.opts.tokenCache.clear().catch(() => undefined);\n return null;\n }\n this.token = entry.accessToken;\n this.expiresAt = entry.expiresAt;\n return this.token;\n }\n\n private async writeCachedToken(): Promise<void> {\n if (!this.opts.tokenCache || !this.token) return;\n await this.opts.tokenCache.write({\n accessToken: this.token,\n expiresAt: this.expiresAt,\n clientId: this.opts.clientId,\n tokenEndpoint: this.opts.tokenEndpoint,\n scope: this.opts.scope,\n });\n }\n}\n","import type { DocmanaConfig } from \"./types.js\";\nimport type { TokenCache } from \"./types.js\";\n\nexport const DEFAULTS = {\n apiBaseUrl: \"https://api.docmana.ai\",\n tokenEndpoint:\n \"https://4fe70f5b-e013-4f65-9fa7-3109a33beba5.ciamlogin.com/4fe70f5b-e013-4f65-9fa7-3109a33beba5/oauth2/v2.0/token\",\n scope: \"api://d781e6ba-cc08-4618-8099-ad968abd2b9e/.default\",\n timeoutMs: 300_000,\n pollIntervalMs: 2_000,\n} as const;\n\nexport interface ResolvedConfig {\n clientId: string;\n clientSecret: string;\n apiBaseUrl: string;\n tokenEndpoint: string;\n scope: string;\n timeoutMs: number;\n pollIntervalMs: number;\n fetchImpl: typeof fetch;\n headers: Record<string, string>;\n tokenCache?: TokenCache;\n}\n\nexport function resolveConfig(config: DocmanaConfig): ResolvedConfig {\n if (!config.clientId) throw new Error(\"DocmanaConfig.clientId is required\");\n if (!config.clientSecret) throw new Error(\"DocmanaConfig.clientSecret is required\");\n const apiBaseUrl = (config.apiBaseUrl ?? DEFAULTS.apiBaseUrl).replace(/\\/+$/, \"\");\n return {\n clientId: config.clientId,\n clientSecret: config.clientSecret,\n apiBaseUrl,\n tokenEndpoint: config.tokenEndpoint ?? DEFAULTS.tokenEndpoint,\n scope: config.scope ?? DEFAULTS.scope,\n timeoutMs: config.timeoutMs ?? DEFAULTS.timeoutMs,\n pollIntervalMs: config.pollIntervalMs ?? DEFAULTS.pollIntervalMs,\n fetchImpl: config.fetch ?? fetch,\n headers: config.headers ?? {},\n tokenCache: config.tokenCache,\n };\n}\n","import type { TokenManager } from \"../auth/token-manager.js\";\nimport { DocmanaError, DocmanaAbortError, errorFromResponse } from \"../errors.js\";\n\nexport interface HttpClientOptions {\n apiBaseUrl: string;\n fetchImpl: typeof fetch;\n tokenManager: TokenManager;\n headers?: Record<string, string>;\n}\n\ntype FetchBody = NonNullable<Parameters<typeof fetch>[1]>[\"body\"];\n\nexport interface RequestOptions {\n query?: Record<string, string>;\n body?: FetchBody;\n headers?: Record<string, string>;\n signal?: AbortSignal;\n}\n\nexport class HttpClient {\n constructor(private readonly opts: HttpClientOptions) {}\n\n async requestJson<T>(method: string, path: string, options: RequestOptions = {}): Promise<T> {\n const res = await this.requestRaw(method, path, options);\n const text = await res.text();\n if (!text) return {} as T;\n try {\n return JSON.parse(text) as T;\n } catch {\n throw new DocmanaError(\"Invalid JSON response from Docmana\", { status: res.status });\n }\n }\n\n async requestRaw(method: string, path: string, options: RequestOptions = {}): Promise<Response> {\n let res = await this.send(method, path, options);\n if (res.status === 401) {\n this.opts.tokenManager.invalidate();\n res = await this.send(method, path, options);\n }\n if (!res.ok) {\n const requestId = res.headers.get(\"x-request-id\") ?? undefined;\n const message = await this.extractMessage(res);\n throw errorFromResponse(res.status, message, requestId);\n }\n return res;\n }\n\n private async send(method: string, path: string, options: RequestOptions): Promise<Response> {\n const token = await this.opts.tokenManager.getToken();\n const url = new URL(this.opts.apiBaseUrl + path);\n for (const [k, v] of Object.entries(options.query ?? {})) url.searchParams.set(k, v);\n const headers: Record<string, string> = {\n ...(this.opts.headers ?? {}),\n authorization: `Bearer ${token}`,\n ...(options.headers ?? {}),\n };\n try {\n return await this.opts.fetchImpl(url, {\n method,\n headers,\n body: options.body,\n signal: options.signal,\n });\n } catch (err) {\n if (options.signal?.aborted || (err instanceof Error && err.name === \"AbortError\")) {\n throw new DocmanaAbortError(\"Request aborted\");\n }\n throw err;\n }\n }\n\n private async extractMessage(res: Response): Promise<string> {\n try {\n const data = (await res.clone().json()) as { message?: string; error?: string };\n return data.message ?? data.error ?? res.statusText ?? `HTTP ${res.status}`;\n } catch {\n return res.statusText ?? `HTTP ${res.status}`;\n }\n }\n}\n","import { readFile } from \"node:fs/promises\";\nimport { basename } from \"node:path\";\nimport type { Readable } from \"node:stream\";\nimport type { FileInput, RunFlowInput } from \"../types.js\";\n\nexport interface ResolvedPart {\n data: Blob;\n filename: string;\n contentType: string;\n}\n\nconst CONTENT_TYPES: Record<string, string> = {\n \".pdf\": \"application/pdf\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".tif\": \"image/tiff\",\n \".tiff\": \"image/tiff\",\n \".txt\": \"text/plain\",\n \".json\": \"application/json\",\n};\n\nfunction contentTypeFor(name: string): string {\n const dot = name.lastIndexOf(\".\");\n if (dot < 0) return \"application/octet-stream\";\n const ext = name.slice(dot).toLowerCase();\n return CONTENT_TYPES[ext] ?? \"application/octet-stream\";\n}\n\nfunction isReadable(x: unknown): x is Readable {\n return typeof x === \"object\" && x !== null && typeof (x as Readable).pipe === \"function\";\n}\n\nfunction isPathInput(x: unknown): x is { path: string } {\n return typeof x === \"object\" && x !== null && typeof (x as { path?: unknown }).path === \"string\";\n}\n\nasync function streamToBuffer(stream: Readable): Promise<Buffer> {\n const chunks: Buffer[] = [];\n for await (const chunk of stream) chunks.push(Buffer.from(chunk));\n return Buffer.concat(chunks);\n}\n\nasync function resolveOne(input: FileInput, fallbackName: string): Promise<ResolvedPart> {\n if (typeof input === \"string\" || isPathInput(input)) {\n const path = typeof input === \"string\" ? input : input.path;\n const data = await readFile(path);\n const filename = basename(path);\n return { data: new Blob([data]), filename, contentType: contentTypeFor(filename) };\n }\n if (input instanceof Uint8Array) {\n return {\n data: new Blob([input]),\n filename: fallbackName,\n contentType: contentTypeFor(fallbackName),\n };\n }\n if (isReadable(input)) {\n const buf = await streamToBuffer(input);\n return {\n data: new Blob([buf]),\n filename: fallbackName,\n contentType: contentTypeFor(fallbackName),\n };\n }\n throw new Error(\"Unsupported file input type\");\n}\n\nexport async function resolveInputs(input: RunFlowInput): Promise<ResolvedPart[]> {\n const list: FileInput[] = input.files ?? (input.file !== undefined ? [input.file] : []);\n if (list.length === 0) throw new Error(\"runFlow requires `file` or `files`\");\n const fallback = input.fileName ?? \"upload.bin\";\n return Promise.all(list.map((item) => resolveOne(item, fallback)));\n}\n","import type { HttpClient } from \"../http/http-client.js\";\nimport type { ResolvedPart } from \"../files/resolve-input.js\";\n\nexport async function uploadFiles(\n http: HttpClient,\n parts: ResolvedPart[],\n signal?: AbortSignal,\n): Promise<string[]> {\n const ids: string[] = [];\n for (const part of parts) {\n const form = new FormData();\n form.append(\"files\", new File([part.data], part.filename, { type: part.contentType }));\n const res = await http.requestJson<{ id: string }>(\"POST\", \"/upload\", { body: form, signal });\n ids.push(res.id);\n }\n return ids;\n}\n","import type { HttpClient } from \"../http/http-client.js\";\n\nexport async function runFlow(\n http: HttpClient,\n flowId: string,\n uuidFiles: string[],\n signal?: AbortSignal,\n once = false,\n): Promise<string> {\n const path = once ? `/flows/run_once_flow/${flowId}` : `/flows/run_flow/${flowId}`;\n const res = await http.requestJson<{ execution_result_id: string }>(\"POST\", path, {\n query: { async_mode: \"true\" },\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ uuid_files: uuidFiles }),\n signal,\n });\n return res.execution_result_id;\n}\n","import type { HttpClient } from \"../http/http-client.js\";\nimport type { ExecutionStatus } from \"../types.js\";\n\nexport async function getStatus(\n http: HttpClient,\n executionResultId: string,\n signal?: AbortSignal,\n): Promise<{ status: ExecutionStatus | string }> {\n return http.requestJson(\"GET\", `/flows/execution-status/${executionResultId}`, { signal });\n}\n","import type { HttpClient } from \"../http/http-client.js\";\nimport type { ExecutionResult } from \"../types.js\";\n\nexport async function getResult(\n http: HttpClient,\n executionResultId: string,\n signal?: AbortSignal,\n): Promise<ExecutionResult> {\n return http.requestJson(\"GET\", `/flows/execution-result/${executionResultId}`, { signal });\n}\n","import { DocmanaTimeoutError, DocmanaAbortError } from \"../errors.js\";\n\nconst TERMINAL = new Set([\"Completed\", \"Failed\"]);\n\nexport interface PollOptions {\n check: () => Promise<string>;\n intervalMs: number;\n timeoutMs: number;\n sleep?: (ms: number) => Promise<void>;\n elapsed?: () => number;\n signal?: AbortSignal;\n}\n\nconst defaultSleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));\n\nexport async function pollUntilTerminal(opts: PollOptions): Promise<string> {\n const sleep = opts.sleep ?? defaultSleep;\n const start = Date.now();\n const elapsed = opts.elapsed ?? (() => Date.now() - start);\n for (;;) {\n if (opts.signal?.aborted) throw new DocmanaAbortError(\"Polling aborted\");\n const status = await opts.check();\n if (TERMINAL.has(status)) return status;\n if (elapsed() >= opts.timeoutMs) {\n throw new DocmanaTimeoutError(`Execution did not finish within ${opts.timeoutMs}ms`);\n }\n await sleep(opts.intervalMs);\n }\n}\n","import { resolveConfig } from \"./config.js\";\nimport type { ResolvedConfig } from \"./config.js\";\nimport type { DocmanaConfig, ExecutionResult, ExecutionStatus, RunFlowInput } from \"./types.js\";\nimport { TokenManager } from \"./auth/token-manager.js\";\nimport { HttpClient } from \"./http/http-client.js\";\nimport { resolveInputs } from \"./files/resolve-input.js\";\nimport { uploadFiles } from \"./api/upload.js\";\nimport { runFlow as runFlowApi } from \"./api/run-flow.js\";\nimport { getStatus as getStatusApi } from \"./api/execution-status.js\";\nimport { getResult as getResultApi } from \"./api/execution-result.js\";\nimport { pollUntilTerminal } from \"./polling/poll.js\";\nimport { DocmanaExecutionError } from \"./errors.js\";\n\nexport class Docmana {\n private readonly config: ResolvedConfig;\n private readonly http: HttpClient;\n\n constructor(config: DocmanaConfig) {\n this.config = resolveConfig(config);\n const tokenManager = new TokenManager({\n clientId: this.config.clientId,\n clientSecret: this.config.clientSecret,\n tokenEndpoint: this.config.tokenEndpoint,\n scope: this.config.scope,\n fetchImpl: this.config.fetchImpl,\n tokenCache: this.config.tokenCache,\n });\n this.http = new HttpClient({\n apiBaseUrl: this.config.apiBaseUrl,\n fetchImpl: this.config.fetchImpl,\n tokenManager,\n headers: this.config.headers,\n });\n }\n\n async runFlowAsync(\n flowId: string,\n input: RunFlowInput,\n ): Promise<{ executionResultId: string; fileIds: string[] }> {\n const parts = await resolveInputs(input);\n const fileIds = await uploadFiles(this.http, parts, input.signal);\n const executionResultId = await runFlowApi(\n this.http,\n flowId,\n fileIds,\n input.signal,\n input.once ?? false,\n );\n return { executionResultId, fileIds };\n }\n\n async getStatus(\n executionResultId: string,\n signal?: AbortSignal,\n ): Promise<{ status: ExecutionStatus | string }> {\n return getStatusApi(this.http, executionResultId, signal);\n }\n\n async getResult(executionResultId: string, signal?: AbortSignal): Promise<ExecutionResult> {\n return getResultApi(this.http, executionResultId, signal);\n }\n\n async runFlow(flowId: string, input: RunFlowInput): Promise<ExecutionResult> {\n const { executionResultId } = await this.runFlowAsync(flowId, input);\n await pollUntilTerminal({\n check: async () => (await this.getStatus(executionResultId, input.signal)).status,\n intervalMs: input.pollIntervalMs ?? this.config.pollIntervalMs,\n timeoutMs: input.timeoutMs ?? this.config.timeoutMs,\n signal: input.signal,\n });\n const result = await this.getResult(executionResultId, input.signal);\n if (result.status === \"Failed\") {\n throw new DocmanaExecutionError(`Flow ${flowId} execution failed`, result.errors ?? []);\n }\n return result;\n }\n}\n"],"mappings":";;;AACA,SAAS,YAAY,oBAAoB;AACzC,SAAS,OAAO,YAAAA,WAAU,IAAI,iBAAiB;AAC/C,SAAS,SAAS,eAAe;AACjC,SAAS,uBAAuB;AAChC,SAAS,qBAAqB;AAC9B,SAAS,SAAS,sBAAsB;;;ACNjC,IAAM,eAAN,cAA2B,MAAM;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACT,YAAY,SAAiB,OAA+D,CAAC,GAAG;AAC9F,UAAM,OAAO;AACb,SAAK,OAAO,WAAW;AACvB,SAAK,SAAS,KAAK;AACnB,SAAK,YAAY,KAAK;AACtB,SAAK,OAAO,KAAK,QAAQ;AACzB,WAAO,eAAe,MAAM,WAAW,SAAS;AAAA,EAClD;AACF;AAEO,IAAM,mBAAN,cAA+B,aAAa;AAAA,EACjD,YAAY,SAAiB,OAAgD,CAAC,GAAG;AAC/E,UAAM,SAAS,EAAE,GAAG,MAAM,MAAM,aAAa,CAAC;AAAA,EAChD;AACF;AAEO,IAAM,yBAAN,cAAqC,aAAa;AAAA,EACvD,YAAY,SAAiB,OAAgD,CAAC,GAAG;AAC/E,UAAM,SAAS,EAAE,GAAG,MAAM,MAAM,mBAAmB,CAAC;AAAA,EACtD;AACF;AAEO,IAAM,uBAAN,cAAmC,aAAa;AAAA,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IAAI,CAAC;AAAA;AAC5B;AAEA,SAAS,qBAAqB,SAAsC;AAClE,MAAI,CAAC,MAAM,QAAQ,OAAO,KAAK,QAAQ,WAAW,EAAG,QAAO;AAC5D,QAAM,UAAU,KAAK,UAAU,QAAQ,MAAM,GAAG,CAAC,GAAG,MAAM,CAAC;AAC3D,MAAI,CAAC,QAAS,QAAO;AACrB,SAAO,QAAQ,SAAS,MAAQ,GAAG,QAAQ,MAAM,GAAG,GAAK,CAAC;AAAA,OAAU;AACtE;AAEA,SAAS,mBAAmB,KAAsB;AAChD,MAAI,eAAe,uBAAuB;AACxC,UAAM,UAAU,IAAI,OAAO,SAAS,IAAI,KAAK,IAAI,OAAO,MAAM,eAAe;AAC7E,WAAO,GAAG,IAAI,OAAO,GAAG,OAAO;AAAA,EACjC;AACA,MAAI,eAAe,aAAc,QAAO,IAAI;AAC5C,MAAI,eAAe,MAAO,QAAO,IAAI;AACrC,SAAO;AACT;AAEA,SAAS,cAAuB;AAC9B,QAAM,QAAQ,QAAQ,KAAK,CAAC;AAC5B,MAAI,CAAC,MAAO,QAAO;AACnB,MAAI;AACF,WAAO,aAAa,QAAQ,KAAK,CAAC,MAAM,aAAa,cAAc,YAAY,GAAG,CAAC;AAAA,EACrF,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,IAAI,YAAY,GAAG;AACjB,SAAO,EAAE,KAAK,CAAC,SAAS;AACtB,YAAQ,WAAW;AAAA,EACrB,CAAC;AACH;","names":["readFile","readFile"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
interface DocmanaConfig {
|
|
2
|
+
clientId: string;
|
|
3
|
+
clientSecret: string;
|
|
4
|
+
apiBaseUrl?: string;
|
|
5
|
+
tokenEndpoint?: string;
|
|
6
|
+
scope?: string;
|
|
7
|
+
timeoutMs?: number;
|
|
8
|
+
pollIntervalMs?: number;
|
|
9
|
+
fetch?: typeof fetch;
|
|
10
|
+
headers?: Record<string, string>;
|
|
11
|
+
tokenCache?: TokenCache;
|
|
12
|
+
}
|
|
13
|
+
interface TokenCacheEntry {
|
|
14
|
+
accessToken: string;
|
|
15
|
+
expiresAt: number;
|
|
16
|
+
clientId: string;
|
|
17
|
+
tokenEndpoint: string;
|
|
18
|
+
scope: string;
|
|
19
|
+
}
|
|
20
|
+
interface TokenCache {
|
|
21
|
+
read(): Promise<TokenCacheEntry | null>;
|
|
22
|
+
write(entry: TokenCacheEntry): Promise<void>;
|
|
23
|
+
clear(): Promise<void>;
|
|
24
|
+
}
|
|
25
|
+
interface PathFileInput {
|
|
26
|
+
path: string;
|
|
27
|
+
}
|
|
28
|
+
type FileInput = string | PathFileInput | Uint8Array | NodeJS.ReadableStream;
|
|
29
|
+
interface RunFlowInput {
|
|
30
|
+
file?: FileInput;
|
|
31
|
+
files?: FileInput[];
|
|
32
|
+
fileName?: string;
|
|
33
|
+
signal?: AbortSignal;
|
|
34
|
+
timeoutMs?: number;
|
|
35
|
+
pollIntervalMs?: number;
|
|
36
|
+
once?: boolean;
|
|
37
|
+
}
|
|
38
|
+
type ExecutionStatus = "Pending" | "Running" | "Incompleted" | "Completed" | "Failed";
|
|
39
|
+
interface ExecutionResult {
|
|
40
|
+
status: ExecutionStatus | string;
|
|
41
|
+
execution_id?: string;
|
|
42
|
+
results?: unknown[];
|
|
43
|
+
errors?: unknown[];
|
|
44
|
+
[key: string]: unknown;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
declare class Docmana {
|
|
48
|
+
private readonly config;
|
|
49
|
+
private readonly http;
|
|
50
|
+
constructor(config: DocmanaConfig);
|
|
51
|
+
runFlowAsync(flowId: string, input: RunFlowInput): Promise<{
|
|
52
|
+
executionResultId: string;
|
|
53
|
+
fileIds: string[];
|
|
54
|
+
}>;
|
|
55
|
+
getStatus(executionResultId: string, signal?: AbortSignal): Promise<{
|
|
56
|
+
status: ExecutionStatus | string;
|
|
57
|
+
}>;
|
|
58
|
+
getResult(executionResultId: string, signal?: AbortSignal): Promise<ExecutionResult>;
|
|
59
|
+
runFlow(flowId: string, input: RunFlowInput): Promise<ExecutionResult>;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
declare class DocmanaError extends Error {
|
|
63
|
+
readonly status?: number;
|
|
64
|
+
readonly requestId?: string;
|
|
65
|
+
readonly code: string;
|
|
66
|
+
constructor(message: string, opts?: {
|
|
67
|
+
status?: number;
|
|
68
|
+
requestId?: string;
|
|
69
|
+
code?: string;
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
declare class DocmanaAuthError extends DocmanaError {
|
|
73
|
+
constructor(message: string, opts?: {
|
|
74
|
+
status?: number;
|
|
75
|
+
requestId?: string;
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
declare class DocmanaPermissionError extends DocmanaError {
|
|
79
|
+
constructor(message: string, opts?: {
|
|
80
|
+
status?: number;
|
|
81
|
+
requestId?: string;
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
declare class DocmanaNotFoundError extends DocmanaError {
|
|
85
|
+
constructor(message: string, opts?: {
|
|
86
|
+
status?: number;
|
|
87
|
+
requestId?: string;
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
declare class DocmanaRequestError extends DocmanaError {
|
|
91
|
+
constructor(message: string, opts?: {
|
|
92
|
+
status?: number;
|
|
93
|
+
requestId?: string;
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
declare class DocmanaExecutionError extends DocmanaError {
|
|
97
|
+
readonly errors: unknown[];
|
|
98
|
+
constructor(message: string, errors?: unknown[]);
|
|
99
|
+
}
|
|
100
|
+
declare class DocmanaTimeoutError extends DocmanaError {
|
|
101
|
+
constructor(message: string);
|
|
102
|
+
}
|
|
103
|
+
declare class DocmanaAbortError extends DocmanaError {
|
|
104
|
+
constructor(message: string);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export { Docmana, DocmanaAbortError, DocmanaAuthError, type DocmanaConfig, DocmanaError, DocmanaExecutionError, DocmanaNotFoundError, DocmanaPermissionError, DocmanaRequestError, DocmanaTimeoutError, type ExecutionResult, type ExecutionStatus, type FileInput, type RunFlowInput };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
interface DocmanaConfig {
|
|
2
|
+
clientId: string;
|
|
3
|
+
clientSecret: string;
|
|
4
|
+
apiBaseUrl?: string;
|
|
5
|
+
tokenEndpoint?: string;
|
|
6
|
+
scope?: string;
|
|
7
|
+
timeoutMs?: number;
|
|
8
|
+
pollIntervalMs?: number;
|
|
9
|
+
fetch?: typeof fetch;
|
|
10
|
+
headers?: Record<string, string>;
|
|
11
|
+
tokenCache?: TokenCache;
|
|
12
|
+
}
|
|
13
|
+
interface TokenCacheEntry {
|
|
14
|
+
accessToken: string;
|
|
15
|
+
expiresAt: number;
|
|
16
|
+
clientId: string;
|
|
17
|
+
tokenEndpoint: string;
|
|
18
|
+
scope: string;
|
|
19
|
+
}
|
|
20
|
+
interface TokenCache {
|
|
21
|
+
read(): Promise<TokenCacheEntry | null>;
|
|
22
|
+
write(entry: TokenCacheEntry): Promise<void>;
|
|
23
|
+
clear(): Promise<void>;
|
|
24
|
+
}
|
|
25
|
+
interface PathFileInput {
|
|
26
|
+
path: string;
|
|
27
|
+
}
|
|
28
|
+
type FileInput = string | PathFileInput | Uint8Array | NodeJS.ReadableStream;
|
|
29
|
+
interface RunFlowInput {
|
|
30
|
+
file?: FileInput;
|
|
31
|
+
files?: FileInput[];
|
|
32
|
+
fileName?: string;
|
|
33
|
+
signal?: AbortSignal;
|
|
34
|
+
timeoutMs?: number;
|
|
35
|
+
pollIntervalMs?: number;
|
|
36
|
+
once?: boolean;
|
|
37
|
+
}
|
|
38
|
+
type ExecutionStatus = "Pending" | "Running" | "Incompleted" | "Completed" | "Failed";
|
|
39
|
+
interface ExecutionResult {
|
|
40
|
+
status: ExecutionStatus | string;
|
|
41
|
+
execution_id?: string;
|
|
42
|
+
results?: unknown[];
|
|
43
|
+
errors?: unknown[];
|
|
44
|
+
[key: string]: unknown;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
declare class Docmana {
|
|
48
|
+
private readonly config;
|
|
49
|
+
private readonly http;
|
|
50
|
+
constructor(config: DocmanaConfig);
|
|
51
|
+
runFlowAsync(flowId: string, input: RunFlowInput): Promise<{
|
|
52
|
+
executionResultId: string;
|
|
53
|
+
fileIds: string[];
|
|
54
|
+
}>;
|
|
55
|
+
getStatus(executionResultId: string, signal?: AbortSignal): Promise<{
|
|
56
|
+
status: ExecutionStatus | string;
|
|
57
|
+
}>;
|
|
58
|
+
getResult(executionResultId: string, signal?: AbortSignal): Promise<ExecutionResult>;
|
|
59
|
+
runFlow(flowId: string, input: RunFlowInput): Promise<ExecutionResult>;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
declare class DocmanaError extends Error {
|
|
63
|
+
readonly status?: number;
|
|
64
|
+
readonly requestId?: string;
|
|
65
|
+
readonly code: string;
|
|
66
|
+
constructor(message: string, opts?: {
|
|
67
|
+
status?: number;
|
|
68
|
+
requestId?: string;
|
|
69
|
+
code?: string;
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
declare class DocmanaAuthError extends DocmanaError {
|
|
73
|
+
constructor(message: string, opts?: {
|
|
74
|
+
status?: number;
|
|
75
|
+
requestId?: string;
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
declare class DocmanaPermissionError extends DocmanaError {
|
|
79
|
+
constructor(message: string, opts?: {
|
|
80
|
+
status?: number;
|
|
81
|
+
requestId?: string;
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
declare class DocmanaNotFoundError extends DocmanaError {
|
|
85
|
+
constructor(message: string, opts?: {
|
|
86
|
+
status?: number;
|
|
87
|
+
requestId?: string;
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
declare class DocmanaRequestError extends DocmanaError {
|
|
91
|
+
constructor(message: string, opts?: {
|
|
92
|
+
status?: number;
|
|
93
|
+
requestId?: string;
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
declare class DocmanaExecutionError extends DocmanaError {
|
|
97
|
+
readonly errors: unknown[];
|
|
98
|
+
constructor(message: string, errors?: unknown[]);
|
|
99
|
+
}
|
|
100
|
+
declare class DocmanaTimeoutError extends DocmanaError {
|
|
101
|
+
constructor(message: string);
|
|
102
|
+
}
|
|
103
|
+
declare class DocmanaAbortError extends DocmanaError {
|
|
104
|
+
constructor(message: string);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export { Docmana, DocmanaAbortError, DocmanaAuthError, type DocmanaConfig, DocmanaError, DocmanaExecutionError, DocmanaNotFoundError, DocmanaPermissionError, DocmanaRequestError, DocmanaTimeoutError, type ExecutionResult, type ExecutionStatus, type FileInput, type RunFlowInput };
|