@jini-ai/integrations 0.4.2 → 0.4.3

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.
Files changed (116) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/api-connections/access-token.d.ts +9 -0
  3. package/dist/api-connections/access-token.js +92 -0
  4. package/dist/api-connections/account-actions.d.ts +40 -0
  5. package/dist/api-connections/account-actions.js +110 -0
  6. package/dist/api-connections/attempt-state.d.ts +28 -0
  7. package/dist/api-connections/attempt-state.js +73 -0
  8. package/dist/api-connections/authorization.d.ts +45 -0
  9. package/dist/api-connections/authorization.js +120 -0
  10. package/dist/api-connections/deps.d.ts +41 -0
  11. package/dist/api-connections/deps.js +13 -0
  12. package/dist/api-connections/descriptor.d.ts +6 -0
  13. package/dist/api-connections/descriptor.js +111 -0
  14. package/dist/api-connections/errors.d.ts +23 -0
  15. package/dist/api-connections/errors.js +24 -0
  16. package/dist/api-connections/finish-authorization.d.ts +24 -0
  17. package/dist/api-connections/finish-authorization.js +117 -0
  18. package/dist/api-connections/index.d.ts +18 -0
  19. package/dist/api-connections/index.js +10 -0
  20. package/dist/api-connections/install-credential.d.ts +19 -0
  21. package/dist/api-connections/install-credential.js +12 -0
  22. package/dist/api-connections/keys.d.ts +27 -0
  23. package/dist/api-connections/keys.js +22 -0
  24. package/dist/api-connections/ports.d.ts +73 -0
  25. package/dist/api-connections/ports.js +2 -0
  26. package/dist/api-connections/records.d.ts +27 -0
  27. package/dist/api-connections/records.js +52 -0
  28. package/dist/api-connections/request-checks.d.ts +18 -0
  29. package/dist/api-connections/request-checks.js +67 -0
  30. package/dist/api-connections/service.d.ts +25 -0
  31. package/dist/api-connections/service.js +26 -0
  32. package/dist/api-connections/status.d.ts +28 -0
  33. package/dist/api-connections/status.js +36 -0
  34. package/dist/api-connections/token-store/errors.d.ts +20 -0
  35. package/dist/api-connections/token-store/errors.js +38 -0
  36. package/dist/api-connections/token-store/index.d.ts +6 -0
  37. package/dist/api-connections/token-store/index.js +6 -0
  38. package/dist/api-connections/token-store/record.d.ts +69 -0
  39. package/dist/api-connections/token-store/record.js +97 -0
  40. package/dist/api-connections/token-store/vault-token-store.d.ts +26 -0
  41. package/dist/api-connections/token-store/vault-token-store.js +215 -0
  42. package/dist/api-connections/types.d.ts +101 -0
  43. package/dist/api-connections/types.js +9 -0
  44. package/dist/credentialed-http/auth-schemes.js +8 -4
  45. package/dist/credentialed-http/credentialed-request.js +47 -77
  46. package/dist/credentialed-http/response-redaction.d.ts +5 -0
  47. package/dist/credentialed-http/response-redaction.js +62 -0
  48. package/dist/media-providers/catalog.d.ts +3 -1
  49. package/dist/media-providers/catalog.js +3 -1
  50. package/dist/media-providers/dispatch/async-operation-store.d.ts +31 -0
  51. package/dist/media-providers/dispatch/async-operation-store.js +75 -37
  52. package/dist/media-providers/dispatch/builtin-vendors.d.ts +1 -1
  53. package/dist/media-providers/dispatch/context.js +10 -2
  54. package/dist/media-providers/dispatch/engine.d.ts +6 -3
  55. package/dist/media-providers/dispatch/engine.js +99 -109
  56. package/dist/media-providers/dispatch/index.d.ts +4 -2
  57. package/dist/media-providers/dispatch/index.js +3 -1
  58. package/dist/media-providers/dispatch/media-provider-registry.d.ts +62 -0
  59. package/dist/media-providers/dispatch/media-provider-registry.js +141 -0
  60. package/dist/media-providers/dispatch/node.d.ts +13 -0
  61. package/dist/media-providers/dispatch/node.js +24 -0
  62. package/dist/media-providers/dispatch/openai-compatible.d.ts +1 -1
  63. package/dist/media-providers/dispatch/openai-compatible.js +90 -87
  64. package/dist/media-providers/dispatch/operation-runtime.js +116 -89
  65. package/dist/media-providers/dispatch/outbound.d.ts +8 -4
  66. package/dist/media-providers/dispatch/outbound.js +27 -26
  67. package/dist/media-providers/dispatch/providers/aihubmix.d.ts +1 -1
  68. package/dist/media-providers/dispatch/providers/aihubmix.js +61 -56
  69. package/dist/media-providers/dispatch/providers/custom-image.d.ts +1 -1
  70. package/dist/media-providers/dispatch/providers/elevenlabs.d.ts +1 -1
  71. package/dist/media-providers/dispatch/providers/fishaudio.d.ts +1 -1
  72. package/dist/media-providers/dispatch/providers/grok.d.ts +1 -1
  73. package/dist/media-providers/dispatch/providers/imagerouter-video-async.d.ts +1 -1
  74. package/dist/media-providers/dispatch/providers/imagerouter-video-async.js +53 -49
  75. package/dist/media-providers/dispatch/providers/imagerouter.d.ts +1 -1
  76. package/dist/media-providers/dispatch/providers/imagerouter.js +11 -24
  77. package/dist/media-providers/dispatch/providers/minimax.d.ts +1 -1
  78. package/dist/media-providers/dispatch/providers/nanobanana.d.ts +1 -1
  79. package/dist/media-providers/dispatch/providers/nanobanana.js +22 -30
  80. package/dist/media-providers/dispatch/providers/openai.d.ts +1 -1
  81. package/dist/media-providers/dispatch/providers/openai.js +51 -47
  82. package/dist/media-providers/dispatch/providers/openrouter.d.ts +1 -1
  83. package/dist/media-providers/dispatch/providers/openrouter.js +52 -37
  84. package/dist/media-providers/dispatch/providers/senseaudio.d.ts +1 -1
  85. package/dist/media-providers/dispatch/providers/senseaudio.js +47 -28
  86. package/dist/media-providers/dispatch/providers/volcengine.d.ts +1 -1
  87. package/dist/media-providers/dispatch/response-parsers.js +37 -21
  88. package/dist/media-providers/dispatch/sqlite-async-operation-store.js +9 -29
  89. package/dist/media-providers/dispatch/ssrf-guard.d.ts +3 -2
  90. package/dist/media-providers/dispatch/ssrf-guard.js +6 -5
  91. package/dist/media-providers/dispatch/types.d.ts +76 -2
  92. package/dist/media-providers/dispatch/vendor-adapter.d.ts +2 -43
  93. package/dist/media-providers/dispatch/vendor-adapter.js +2 -2
  94. package/dist/media-providers/dispatch/vendor-registry-core.d.ts +24 -0
  95. package/dist/media-providers/dispatch/vendor-registry-core.js +34 -0
  96. package/dist/media-providers/dispatch/vendor-registry.d.ts +10 -36
  97. package/dist/media-providers/dispatch/vendor-registry.js +14 -42
  98. package/dist/media-providers/policy.js +25 -17
  99. package/dist/media-providers/providers.d.ts +5 -0
  100. package/dist/media-providers/providers.js +2 -0
  101. package/dist/media-providers/sqlite-task-store.js +12 -80
  102. package/dist/media-providers/staging.js +77 -58
  103. package/dist/media-providers/task-lifecycle.d.ts +33 -0
  104. package/dist/media-providers/task-lifecycle.js +124 -0
  105. package/dist/media-providers/task-store.js +8 -86
  106. package/dist/media-providers/ui-defaults.d.ts +10 -0
  107. package/dist/media-providers/ui-defaults.js +167 -0
  108. package/dist/media-providers/video-request.js +112 -90
  109. package/dist/webhooks/delivery.d.ts +14 -0
  110. package/dist/webhooks/delivery.js +41 -10
  111. package/dist/webhooks/index.d.ts +1 -0
  112. package/dist/webhooks/index.js +1 -0
  113. package/dist/webhooks/ports.d.ts +23 -0
  114. package/dist/webhooks/worker.d.ts +83 -0
  115. package/dist/webhooks/worker.js +105 -0
  116. package/package.json +31 -8
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Media vendors as provider contributions: one `{ provider, models, adapters }` unit per vendor, held
3
+ * in the shared keyed registry (`@jini-ai/core/provider-registry`, contract `media`).
4
+ *
5
+ * Why: the catalogue used to be closed consts (`providers.ts`) enforced by the engine, with adapters
6
+ * registered somewhere else, so a plugin could not add a vendor. The consts are now only the data the
7
+ * built-in contribution is made from; the engine validates against whatever this registry holds.
8
+ *
9
+ * Ids: the shared grammar forbids hyphens and one built-in id has one (`custom-image`), so the
10
+ * registry KEY is the canonical id with `-` -> `_`. The public id on `provider.id` — the one saved
11
+ * credentials, settings and env-var maps use — never changes.
12
+ */
13
+ import { type ProviderDefinition, type ProviderRegistry } from '@jini-ai/core/provider-registry';
14
+ import type { AudioKind, MediaModel, MediaProvider, MediaSurface } from '../types.js';
15
+ import type { MediaModelCatalog, VendorAdapter, VendorAdapterLookup } from './types.js';
16
+ /** A catalogued model plus the surface (and audio kind) it is offered on. */
17
+ export interface MediaProviderModel extends MediaModel {
18
+ readonly surface: MediaSurface;
19
+ readonly audioKind?: AudioKind;
20
+ /** Sort key within a surface; built-ins carry their catalogue index. Unset sorts after, in registration order. */
21
+ readonly order?: number;
22
+ }
23
+ /** Everything one vendor brings, registered as one unit. */
24
+ export interface MediaProviderContribution {
25
+ readonly provider: MediaProvider;
26
+ readonly models: readonly MediaProviderModel[];
27
+ /** Route key (`image`, `video`, `audio:speech`, …) -> the adapter serving it. */
28
+ readonly adapters: Readonly<Record<string, VendorAdapter<never>>>;
29
+ }
30
+ export interface MediaProviderRegistry extends VendorAdapterLookup, MediaModelCatalog {
31
+ /** The shared registry; plugin loaders contribute here (`contributeProviders`). */
32
+ readonly providers: ProviderRegistry<MediaProviderContribution>;
33
+ /** Every registered vendor, registration order. */
34
+ listProviders(_required?: Record<string, never>): readonly MediaProvider[];
35
+ }
36
+ export declare const MEDIA_PROVIDER_CONTRACT = "media";
37
+ /** The registry key for a public media provider id (aliases resolved, `-` -> `_`). @complexity O(n) in id length. */
38
+ export declare function mediaProviderRegistryId({ id }: {
39
+ id: string;
40
+ }, _optional?: Record<string, never>): string;
41
+ /** Wraps one contribution as a shared-registry definition. @complexity O(1). */
42
+ export declare function mediaProviderDefinition({ contribution }: {
43
+ contribution: MediaProviderContribution;
44
+ }, _optional?: Record<string, never>): ProviderDefinition<MediaProviderContribution>;
45
+ /**
46
+ * Builds the media provider registry. Built-ins register with the throwing policy; plugins go through
47
+ * `providers.contribute` (or agent-plugins' `contributeProviders`) and are refused, never thrown.
48
+ * @param optional.contributions - Core contributions; defaults to {@link builtinMediaProviderContributions}.
49
+ * @throws {ProviderRegistryError} When a core contribution is malformed or duplicated.
50
+ * @complexity Lookups O(m) over registered models (tens), registration O(m).
51
+ */
52
+ export declare function createMediaProviderRegistry(_required?: Record<string, never>, { contributions }?: {
53
+ contributions?: readonly MediaProviderContribution[];
54
+ }): MediaProviderRegistry;
55
+ /**
56
+ * Today's built-in vendors as the default contribution set: one unit per `MEDIA_PROVIDERS` entry, its
57
+ * catalogued models, and the adapters its `registerVendorAdapters` registers.
58
+ * @returns Fresh contributions; adapters are the shared module-level adapter objects.
59
+ * @complexity O(p + m + a) providers, models and adapters.
60
+ */
61
+ export declare function builtinMediaProviderContributions(_required?: Record<string, never>): MediaProviderContribution[];
62
+ //# sourceMappingURL=media-provider-registry.d.ts.map
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Media vendors as provider contributions: one `{ provider, models, adapters }` unit per vendor, held
3
+ * in the shared keyed registry (`@jini-ai/core/provider-registry`, contract `media`).
4
+ *
5
+ * Why: the catalogue used to be closed consts (`providers.ts`) enforced by the engine, with adapters
6
+ * registered somewhere else, so a plugin could not add a vendor. The consts are now only the data the
7
+ * built-in contribution is made from; the engine validates against whatever this registry holds.
8
+ *
9
+ * Ids: the shared grammar forbids hyphens and one built-in id has one (`custom-image`), so the
10
+ * registry KEY is the canonical id with `-` -> `_`. The public id on `provider.id` — the one saved
11
+ * credentials, settings and env-var maps use — never changes.
12
+ */
13
+ import { createProviderRegistry, } from '@jini-ai/core/provider-registry';
14
+ import { AUDIO_MODELS_BY_KIND, IMAGE_MODELS, MEDIA_PROVIDERS, VIDEO_MODELS, canonicalMediaProviderId } from '../providers.js';
15
+ import { registerBuiltinVendorAdapters } from './builtin-vendors.js';
16
+ export const MEDIA_PROVIDER_CONTRACT = 'media';
17
+ /** The registry key for a public media provider id (aliases resolved, `-` -> `_`). @complexity O(n) in id length. */
18
+ export function mediaProviderRegistryId({ id }, _optional = {}) {
19
+ return canonicalMediaProviderId({ id }).replaceAll('-', '_');
20
+ }
21
+ /** Wraps one contribution as a shared-registry definition. @complexity O(1). */
22
+ export function mediaProviderDefinition({ contribution }, _optional = {}) {
23
+ return { id: mediaProviderRegistryId({ id: contribution.provider.id }), provider: contribution, label: contribution.provider.label };
24
+ }
25
+ function isAdapter(value) {
26
+ const candidate = value;
27
+ return typeof candidate?.buildRequest === 'function' && typeof candidate.parseResponse === 'function';
28
+ }
29
+ function providerFault(provider) {
30
+ const valid = typeof provider?.id === 'string' && typeof provider.label === 'string' && provider.label.trim() !== '';
31
+ return valid ? undefined : 'provider needs a string id and a non-empty label';
32
+ }
33
+ function modelsFault(models, providerId) {
34
+ if (!Array.isArray(models))
35
+ return 'models must be an array';
36
+ // findIndex, not find: a `find` hit on an `undefined` element is indistinguishable from no hit, which
37
+ // let `models: [undefined]` pass here and then throw in the collision check.
38
+ const at = models.findIndex(model => model?.provider !== providerId || typeof model.id !== 'string' || !model.id);
39
+ return at === -1 ? undefined : `model '${String(models[at]?.id)}' must have an id and belong to provider '${providerId}'`;
40
+ }
41
+ function adaptersFault(adapters) {
42
+ if (typeof adapters !== 'object' || adapters === null)
43
+ return 'adapters must be an object';
44
+ const byRoute = adapters;
45
+ const broken = Object.keys(byRoute).find(routeKey => !isAdapter(byRoute[routeKey]));
46
+ return broken === undefined ? undefined : `adapter for route '${broken}' needs buildRequest and parseResponse functions`;
47
+ }
48
+ /** Shape faults inside one contribution (plugin input is untrusted), independent of what else is registered. */
49
+ function ownFault(contribution) {
50
+ const { provider, models, adapters } = (contribution ?? {});
51
+ return providerFault(provider) ?? modelsFault(models, provider.id) ?? adaptersFault(adapters);
52
+ }
53
+ /**
54
+ * A model id another provider already offers on ANY route. Why not per route: `findModel` (and so
55
+ * dispatch and credential selection) resolves a model by id alone, so a second vendor's `gpt-image-2`
56
+ * on video would be routed to OpenAI — or, with a lower `order`, take OpenAI's image traffic.
57
+ */
58
+ function collisionFault(contribution, registered) {
59
+ const ownKey = mediaProviderRegistryId({ id: contribution.provider.id });
60
+ const taken = new Set(registered.filter(entry => entry.id !== ownKey).flatMap(entry => entry.provider.models.map(model => model.id)));
61
+ const clash = contribution.models.find(model => taken.has(model.id));
62
+ return clash === undefined ? undefined : `model '${clash.id}' is already offered by another provider`;
63
+ }
64
+ function byOrder(left, right) {
65
+ const a = left.model.order ?? Number.MAX_SAFE_INTEGER;
66
+ const b = right.model.order ?? Number.MAX_SAFE_INTEGER;
67
+ return a === b ? left.index - right.index : a - b;
68
+ }
69
+ /** Strips the registry-only fields so callers see the same `MediaModel` shape as the static catalogue. */
70
+ function asMediaModel(model) {
71
+ const { surface: _surface, audioKind: _audioKind, order: _order, ...rest } = model;
72
+ return rest;
73
+ }
74
+ /**
75
+ * Builds the media provider registry. Built-ins register with the throwing policy; plugins go through
76
+ * `providers.contribute` (or agent-plugins' `contributeProviders`) and are refused, never thrown.
77
+ * @param optional.contributions - Core contributions; defaults to {@link builtinMediaProviderContributions}.
78
+ * @throws {ProviderRegistryError} When a core contribution is malformed or duplicated.
79
+ * @complexity Lookups O(m) over registered models (tens), registration O(m).
80
+ */
81
+ export function createMediaProviderRegistry(_required = {}, { contributions = builtinMediaProviderContributions() } = {}) {
82
+ let current;
83
+ const providers = createProviderRegistry({ contract: MEDIA_PROVIDER_CONTRACT }, {
84
+ // `current` is assigned before any registration below; validate only runs from register/contribute.
85
+ validate: ({ provider }) => ownFault(provider) ?? collisionFault(provider, current.list()),
86
+ });
87
+ current = providers;
88
+ for (const contribution of contributions)
89
+ providers.register({ definition: mediaProviderDefinition({ contribution }) });
90
+ const entryFor = (id) => providers.get({ id: mediaProviderRegistryId({ id }) })?.provider;
91
+ const allModels = () => providers.list().flatMap(entry => entry.provider.models).map((model, index) => ({ model, index })).sort(byOrder).map(({ model }) => model);
92
+ return {
93
+ providers,
94
+ get: ({ providerId, routeKey }) => entryFor(providerId)?.adapters[routeKey],
95
+ findModel: ({ id }) => {
96
+ const found = allModels().find(model => model.id === id);
97
+ return found === undefined ? null : asMediaModel(found);
98
+ },
99
+ findProvider: ({ id }) => entryFor(id)?.provider ?? null,
100
+ modelsForSurface: ({ surface }, { audioKind } = {}) => {
101
+ const kind = surface === 'audio' ? audioKind ?? 'music' : undefined;
102
+ return allModels().filter(model => model.surface === surface && (kind === undefined || (model.audioKind ?? 'music') === kind)).map(asMediaModel);
103
+ },
104
+ listProviders: () => providers.list().map(entry => entry.provider.provider),
105
+ };
106
+ }
107
+ /** The static catalogue with each model's surface and catalogue index attached. */
108
+ function builtinModels() {
109
+ const audio = Object.keys(AUDIO_MODELS_BY_KIND).flatMap(audioKind => AUDIO_MODELS_BY_KIND[audioKind].map(model => ({ ...model, surface: 'audio', audioKind })));
110
+ const all = [
111
+ ...IMAGE_MODELS.map(model => ({ ...model, surface: 'image' })),
112
+ ...VIDEO_MODELS.map(model => ({ ...model, surface: 'video' })),
113
+ ...audio,
114
+ ];
115
+ return all.map((model, order) => ({ ...model, order }));
116
+ }
117
+ /**
118
+ * Today's built-in vendors as the default contribution set: one unit per `MEDIA_PROVIDERS` entry, its
119
+ * catalogued models, and the adapters its `registerVendorAdapters` registers.
120
+ * @returns Fresh contributions; adapters are the shared module-level adapter objects.
121
+ * @complexity O(p + m + a) providers, models and adapters.
122
+ */
123
+ export function builtinMediaProviderContributions(_required = {}) {
124
+ const adapters = new Map();
125
+ registerBuiltinVendorAdapters({
126
+ registry: {
127
+ register: ({ providerId, routeKey, adapter }) => {
128
+ const byRoute = adapters.get(providerId) ?? {};
129
+ byRoute[routeKey] = adapter;
130
+ adapters.set(providerId, byRoute);
131
+ },
132
+ },
133
+ });
134
+ const models = builtinModels();
135
+ return MEDIA_PROVIDERS.map(provider => ({
136
+ provider,
137
+ models: models.filter(model => model.provider === provider.id),
138
+ adapters: adapters.get(provider.id) ?? {},
139
+ }));
140
+ }
141
+ //# sourceMappingURL=media-provider-registry.js.map
@@ -0,0 +1,13 @@
1
+ /** Explicit Node adapter entry. Hosts construct this once and inject it into media services. */
2
+ import type { HttpClientPort } from '@jini-ai/core/primitives';
3
+ import type { DnsResolver } from '@jini-ai/platform/http/guarded';
4
+ export interface NodeMediaHttpClientOptions {
5
+ readonly allowPrivateNetwork?: boolean;
6
+ readonly dns?: DnsResolver;
7
+ }
8
+ /** The default policy client: public http(s) peers only unless the caller explicitly opts into
9
+ * private-network development, never following redirects.
10
+ * @returns A DNS-pinned, bounded client; policy and transport failures reject send.
11
+ */
12
+ export declare function createNodeMediaHttpClient(_required: Record<string, never>, { allowPrivateNetwork, dns }?: NodeMediaHttpClientOptions): HttpClientPort;
13
+ //# sourceMappingURL=node.d.ts.map
@@ -0,0 +1,24 @@
1
+ import { FETCH_TIMEOUT_MS } from '@jini-ai/platform/fetch-with-timeout';
2
+ import { createHttpClient, createNodeGuardedHttpPorts } from '@jini-ai/platform/http/guarded';
3
+ /** The default policy client: public http(s) peers only unless the caller explicitly opts into
4
+ * private-network development, never following redirects.
5
+ * @returns A DNS-pinned, bounded client; policy and transport failures reject send.
6
+ */
7
+ export function createNodeMediaHttpClient(_required, { allowPrivateNetwork, dns } = {}) {
8
+ return createHttpClient({
9
+ ...createNodeGuardedHttpPorts({}),
10
+ ...(dns === undefined ? {} : { dns }),
11
+ userAgent: 'media-provider',
12
+ policy: {
13
+ allowedSchemes: ['http', 'https'],
14
+ denyPrivateAddresses: allowPrivateNetwork !== true,
15
+ devHostAllowlist: [],
16
+ maxRedirects: 0,
17
+ connectTimeoutMs: FETCH_TIMEOUT_MS.GENERATE,
18
+ // Media can contain video; bound buffering at 96 MiB. Hosts may inject a stricter policy.
19
+ maxResponseBytes: 96 * 1024 * 1024,
20
+ maxDecompressedBytes: 96 * 1024 * 1024,
21
+ },
22
+ });
23
+ }
24
+ //# sourceMappingURL=node.js.map
@@ -34,7 +34,7 @@ export declare function buildOpenAIImageUrl(baseUrl: string, isAzure: boolean):
34
34
  export declare function buildOpenAIImageEditUrl(baseUrl: string): string;
35
35
  /** Builds the `/videos/generations` URL. */
36
36
  export declare function buildOpenAIVideoUrl(baseUrl: string): string;
37
- /** Picks an image `size` string tuned to the model family + requested aspect ratio. */
37
+ /** Picks an image `size` string tuned to the model family + requested aspect ratio, defaulting to the `1024x1024` square. */
38
38
  export declare function openaiSizeFor(model: string, aspect?: string): string;
39
39
  /** Builds the `/audio/speech` URL, appending the default Azure `api-version` when the caller didn't supply one. */
40
40
  export declare function buildOpenAISpeechUrl(baseUrl: string, isAzure: boolean): string;
@@ -28,26 +28,24 @@ export function withRequestInit(ctx, init = {}) {
28
28
  ...init,
29
29
  };
30
30
  }
31
+ // PNG (`89 50 4E 47`, min 8 bytes) has no entry: it is also the default, so
32
+ // matching it explicitly could never change the result.
33
+ const IMAGE_SIGNATURES = [
34
+ { ext: '.jpg', runs: [[0, [0xff, 0xd8, 0xff]]] },
35
+ {
36
+ ext: '.webp',
37
+ runs: [
38
+ [0, [0x52, 0x49, 0x46, 0x46]], // RIFF
39
+ [8, [0x57, 0x45, 0x42, 0x50]], // WEBP
40
+ ],
41
+ },
42
+ ];
43
+ function matchesSignature(bytes, signature) {
44
+ return signature.runs.every(([offset, magic]) => magic.every((byte, i) => bytes[offset + i] === byte));
45
+ }
31
46
  /** Sniffs an image byte buffer's format from its magic bytes (jpg/png/webp), defaulting to `.png`. */
32
47
  export function sniffImageExt(bytes) {
33
- if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {
34
- return '.jpg';
35
- }
36
- if (bytes.length >= 8 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) {
37
- return '.png';
38
- }
39
- if (bytes.length >= 12 &&
40
- bytes[0] === 0x52 &&
41
- bytes[1] === 0x49 &&
42
- bytes[2] === 0x46 &&
43
- bytes[3] === 0x46 &&
44
- bytes[8] === 0x57 &&
45
- bytes[9] === 0x45 &&
46
- bytes[10] === 0x42 &&
47
- bytes[11] === 0x50) {
48
- return '.webp';
49
- }
50
- return '.png';
48
+ return IMAGE_SIGNATURES.find((signature) => matchesSignature(bytes, signature))?.ext ?? '.png';
51
49
  }
52
50
  export const AZURE_DEFAULT_API_VERSION = '2024-02-01';
53
51
  /**
@@ -75,90 +73,85 @@ export function detectAzureEndpoint(baseUrl) {
75
73
  export function normalizeOpenAICompatiblePath(pathname, endpoint, mode) {
76
74
  const strippedPath = pathname.replace(/\/+$/, '');
77
75
  const generationsSuffix = `/${endpoint}/generations`;
78
- const editsSuffix = endpoint === 'images' ? '/images/edits' : null;
79
- if (strippedPath.endsWith(generationsSuffix)) {
80
- if (mode === 'generations')
81
- return strippedPath;
82
- return endpoint === 'images' ? `${strippedPath.slice(0, -generationsSuffix.length)}${editsSuffix}` : strippedPath;
83
- }
84
- if (editsSuffix && strippedPath.endsWith(editsSuffix)) {
85
- if (mode === 'edits')
86
- return strippedPath;
87
- return `${strippedPath.slice(0, -editsSuffix.length)}${generationsSuffix}`;
88
- }
89
- return mode === 'edits' && editsSuffix ? `${strippedPath}${editsSuffix}` : `${strippedPath}${generationsSuffix}`;
76
+ if (endpoint === 'videos') {
77
+ // Videos have no edits endpoint, so `edits` mode still targets generations.
78
+ return strippedPath.endsWith(generationsSuffix) ? strippedPath : `${strippedPath}${generationsSuffix}`;
79
+ }
80
+ const editsSuffix = '/images/edits';
81
+ const knownSuffix = [generationsSuffix, editsSuffix].find((suffix) => strippedPath.endsWith(suffix));
82
+ const prefix = knownSuffix ? strippedPath.slice(0, -knownSuffix.length) : strippedPath;
83
+ return `${prefix}${mode === 'edits' ? editsSuffix : generationsSuffix}`;
90
84
  }
91
- /** Builds the full `/{endpoint}/generations` URL, preserving any user-supplied query string. */
92
- export function buildOpenAICompatibleGenerationUrl(baseUrl, endpoint) {
85
+ /** Points `baseUrl`'s path at the given endpoint/mode, keeping any query string; an unparseable base URL is normalized as a bare path. */
86
+ function buildOpenAICompatibleUrl(baseUrl, endpoint, mode) {
93
87
  let parsed;
94
88
  try {
95
89
  parsed = new URL(baseUrl);
96
90
  }
97
91
  catch {
98
- const stripped = baseUrl.replace(/\/$/, '');
99
- return normalizeOpenAICompatiblePath(stripped, endpoint, 'generations');
92
+ return normalizeOpenAICompatiblePath(baseUrl, endpoint, mode);
100
93
  }
101
- parsed.pathname = normalizeOpenAICompatiblePath(parsed.pathname, endpoint, 'generations');
94
+ parsed.pathname = normalizeOpenAICompatiblePath(parsed.pathname, endpoint, mode);
102
95
  return parsed.toString();
103
96
  }
97
+ /** Appends the default Azure `api-version` when the endpoint is Azure and the caller didn't supply one. */
98
+ function applyDefaultAzureApiVersion(parsed, isAzure) {
99
+ if (isAzure && !parsed.searchParams.has('api-version')) {
100
+ parsed.searchParams.set('api-version', AZURE_DEFAULT_API_VERSION);
101
+ }
102
+ }
103
+ /** Builds the full `/{endpoint}/generations` URL, preserving any user-supplied query string. */
104
+ export function buildOpenAICompatibleGenerationUrl(baseUrl, endpoint) {
105
+ return buildOpenAICompatibleUrl(baseUrl, endpoint, 'generations');
106
+ }
104
107
  /** Builds the `/images/generations` URL, appending the default Azure `api-version` when the caller didn't supply one. */
105
108
  export function buildOpenAIImageUrl(baseUrl, isAzure) {
109
+ const url = buildOpenAICompatibleGenerationUrl(baseUrl, 'images');
106
110
  let parsed;
107
111
  try {
108
- parsed = new URL(buildOpenAICompatibleGenerationUrl(baseUrl, 'images'));
112
+ parsed = new URL(url);
109
113
  }
110
114
  catch {
111
115
  // Bad URL — fall back to naive concat so the upstream error is
112
116
  // surfaced through the normal HTTP path rather than a parse crash.
113
- return buildOpenAICompatibleGenerationUrl(baseUrl, 'images');
114
- }
115
- if (isAzure && !parsed.searchParams.has('api-version')) {
116
- parsed.searchParams.set('api-version', AZURE_DEFAULT_API_VERSION);
117
+ return url;
117
118
  }
119
+ applyDefaultAzureApiVersion(parsed, isAzure);
118
120
  return parsed.toString();
119
121
  }
120
122
  /** Builds the `/images/edits` URL (used when a reference image is present). */
121
123
  export function buildOpenAIImageEditUrl(baseUrl) {
122
- let parsed;
123
- try {
124
- parsed = new URL(baseUrl);
125
- }
126
- catch {
127
- const stripped = baseUrl.replace(/\/$/, '');
128
- return normalizeOpenAICompatiblePath(stripped, 'images', 'edits');
129
- }
130
- parsed.pathname = normalizeOpenAICompatiblePath(parsed.pathname, 'images', 'edits');
131
- return parsed.toString();
124
+ return buildOpenAICompatibleUrl(baseUrl, 'images', 'edits');
132
125
  }
133
126
  /** Builds the `/videos/generations` URL. */
134
127
  export function buildOpenAIVideoUrl(baseUrl) {
135
128
  return buildOpenAICompatibleGenerationUrl(baseUrl, 'videos');
136
129
  }
137
- /** Picks an image `size` string tuned to the model family + requested aspect ratio. */
130
+ // gpt-image-1.5 / gpt-image-2 accept arbitrary sizes up to 4096; concrete
131
+ // sizes tuned to common aspects are picked so the API never negotiates
132
+ // them down silently.
133
+ const GPT_IMAGE_SIZES = new Map([
134
+ ['16:9', '1792x1024'],
135
+ ['9:16', '1024x1792'],
136
+ ['4:3', '1408x1056'],
137
+ ['3:4', '1056x1408'],
138
+ ]);
139
+ const DALLE_3_SIZES = new Map([
140
+ ['16:9', '1792x1024'],
141
+ ['9:16', '1024x1792'],
142
+ ]);
143
+ // dall-e-2 only supports 256/512/1024 squares.
144
+ const SQUARE_ONLY_SIZES = new Map();
145
+ function sizeTableFor(model) {
146
+ if (model.startsWith('gpt-image-'))
147
+ return GPT_IMAGE_SIZES;
148
+ if (model === 'dall-e-3')
149
+ return DALLE_3_SIZES;
150
+ return SQUARE_ONLY_SIZES;
151
+ }
152
+ /** Picks an image `size` string tuned to the model family + requested aspect ratio, defaulting to the `1024x1024` square. */
138
153
  export function openaiSizeFor(model, aspect) {
139
- // gpt-image-1.5 / gpt-image-2 accept arbitrary sizes up to 4096; concrete
140
- // sizes tuned to common aspects are picked so the API never negotiates
141
- // them down silently.
142
- if (model.startsWith('gpt-image-')) {
143
- if (aspect === '16:9')
144
- return '1792x1024';
145
- if (aspect === '9:16')
146
- return '1024x1792';
147
- if (aspect === '4:3')
148
- return '1408x1056';
149
- if (aspect === '3:4')
150
- return '1056x1408';
151
- return '1024x1024';
152
- }
153
- if (model === 'dall-e-3') {
154
- if (aspect === '16:9')
155
- return '1792x1024';
156
- if (aspect === '9:16')
157
- return '1024x1792';
158
- return '1024x1024';
159
- }
160
- // dall-e-2 only supports 256/512/1024 squares.
161
- return '1024x1024';
154
+ return sizeTableFor(model).get(aspect ?? '') ?? '1024x1024';
162
155
  }
163
156
  /** Builds the `/audio/speech` URL, appending the default Azure `api-version` when the caller didn't supply one. */
164
157
  export function buildOpenAISpeechUrl(baseUrl, isAzure) {
@@ -171,9 +164,7 @@ export function buildOpenAISpeechUrl(baseUrl, isAzure) {
171
164
  return `${stripped}/audio/speech`;
172
165
  }
173
166
  parsed.pathname = parsed.pathname.replace(/\/+$/, '') + '/audio/speech';
174
- if (isAzure && !parsed.searchParams.has('api-version')) {
175
- parsed.searchParams.set('api-version', AZURE_DEFAULT_API_VERSION);
176
- }
167
+ applyDefaultAzureApiVersion(parsed, isAzure);
177
168
  return parsed.toString();
178
169
  }
179
170
  /** Parses an OpenAI-compatible JSON response, throwing a clear, provider-tagged error on a non-OK status or non-JSON body. */
@@ -195,24 +186,36 @@ export async function parseOpenAICompatibleJson(resp, providerTag) {
195
186
  * @complexity O(b) time and space for b generated bytes, bounded by outbound policy for downloads.
196
187
  */
197
188
  export async function bytesFromOpenAICompatibleData({ data, providerTag }, { requestInit = {}, ...outbound } = {}) {
198
- const record = data;
199
- const entry = record && Array.isArray(record.data) ? record.data[0] : undefined;
189
+ const entry = firstDataEntry(data);
200
190
  if (!entry)
201
191
  throw new Error(`${providerTag} response had no data[0]`);
202
- if (typeof entry.b64_json === 'string' && entry.b64_json) {
203
- const raw = entry.b64_json.includes(',') ? entry.b64_json.slice(entry.b64_json.indexOf(',') + 1) : entry.b64_json;
204
- return Buffer.from(raw, 'base64');
205
- }
206
- if (typeof entry.url === 'string' && entry.url) {
192
+ const b64Json = stringOrUndefined(entry.b64_json);
193
+ if (b64Json) {
194
+ // A data-URL (`data:<mime>;base64,<payload>`) keeps only what follows its first comma;
195
+ // with no comma `indexOf` is -1, so the whole string is decoded.
196
+ return Buffer.from(b64Json.slice(b64Json.indexOf(',') + 1), 'base64');
197
+ }
198
+ const url = stringOrUndefined(entry.url);
199
+ if (url) {
207
200
  // Downloading already-generated bytes from the vendor's CDN, not waiting on generation itself
208
201
  // — UPLOAD-class (2min), not GENERATE-class (10min): see FETCH_TIMEOUT_MS's own doc.
209
- const mediaResp = await assertAndFetchExternalAsset({ url: entry.url }, { ...outbound, init: requestInit });
202
+ const mediaResp = await assertAndFetchExternalAsset({ url }, { ...outbound, init: requestInit });
210
203
  if (!mediaResp.ok) {
211
204
  throw new Error(`${providerTag} media fetch ${mediaResp.status}`);
212
205
  }
213
- const arr = await mediaResp.arrayBuffer();
214
- return Buffer.from(arr);
206
+ return Buffer.from(await mediaResp.arrayBuffer());
215
207
  }
216
208
  throw new Error(`${providerTag} response had neither b64_json nor url`);
217
209
  }
210
+ /** `data.data[0]` of an OpenAI-compatible response, or `undefined` when the body has no such entry. */
211
+ function firstDataEntry(data) {
212
+ const record = data;
213
+ if (!record || !Array.isArray(record.data))
214
+ return undefined;
215
+ return record.data[0] ?? undefined;
216
+ }
217
+ /** Narrows to a string; callers treat an empty string as absent through their own truthiness check. */
218
+ function stringOrUndefined(value) {
219
+ return typeof value === 'string' ? value : undefined;
220
+ }
218
221
  //# sourceMappingURL=openai-compatible.js.map