@hintergrund/worker 0.3.16 → 0.3.18
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/dist/api/cms/handlers/agent-provider.handler.d.ts +3 -0
- package/dist/api/cms/handlers/agent-provider.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/agent-provider.handler.js +14 -19
- package/dist/api/cms/handlers/github-secrets.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/github-secrets.handler.js +3 -4
- package/dist/api/cms/handlers/setup.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/setup.handler.js +3 -16
- package/dist/api/emails/handlers/settings.handler.d.ts +1 -3
- package/dist/api/emails/handlers/settings.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/settings.handler.js +1 -6
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/lib/integration-health.d.ts +3 -6
- package/dist/lib/integration-health.d.ts.map +1 -1
- package/dist/lib/integration-health.js +18 -9
- package/dist/lib/invoice.js +3 -3
- package/dist/lib/website-i18n.d.ts.map +1 -1
- package/dist/lib/website-i18n.js +56 -18
- package/package.json +10 -2
- package/dist/api/emails/handlers/invoice.handler.d.ts +0 -9
- package/dist/api/emails/handlers/invoice.handler.d.ts.map +0 -1
- package/dist/api/emails/handlers/invoice.handler.js +0 -154
- package/dist/lib/brand.d.ts +0 -6
- package/dist/lib/brand.d.ts.map +0 -1
- package/dist/lib/brand.js +0 -31
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import type { Context } from 'hono';
|
|
2
2
|
import { type AgentProviderName } from '@hintergrund/runtime-contracts';
|
|
3
3
|
import type { Bindings, HonoEnv } from '../../../index';
|
|
4
|
+
/** Presents a provider's key the way its API expects (`AGENT_PROVIDER_CONFIG[provider].auth`). */
|
|
5
|
+
export declare function authorizeProvider(headers: Headers, provider: AgentProviderName, key: string): void;
|
|
6
|
+
export declare function providerKey(env: Bindings, provider: AgentProviderName): string | undefined;
|
|
4
7
|
/** The provider to use, in declaration order, for projects that configure several. */
|
|
5
8
|
export declare function activeAgentProvider(env: Bindings): AgentProviderName | null;
|
|
6
9
|
export declare function getAgentConfig(c: Context<HonoEnv>): Promise<Response>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-provider.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/agent-provider.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,
|
|
1
|
+
{"version":3,"file":"agent-provider.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/agent-provider.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,EAAkE,KAAK,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AACxI,OAAO,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAExD,kGAAkG;AAClG,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,iBAAiB,EAAE,GAAG,EAAE,MAAM,GAAG,IAAI,CAGlG;AAED,wBAAgB,WAAW,CAAC,GAAG,EAAE,QAAQ,EAAE,QAAQ,EAAE,iBAAiB,GAAG,MAAM,GAAG,SAAS,CAK1F;AAED,sFAAsF;AACtF,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,QAAQ,GAAG,iBAAiB,GAAG,IAAI,CAE3E;AAED,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAE3E;AAED;;;GAGG;AACH,wBAAsB,iBAAiB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAkC9E"}
|
|
@@ -1,20 +1,10 @@
|
|
|
1
|
-
import { AGENT_PROVIDERS, AGENT_PROVIDER_SECRETS } from '@hintergrund/runtime-contracts';
|
|
2
|
-
/**
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
google: {
|
|
9
|
-
baseUrl: 'https://generativelanguage.googleapis.com/v1beta',
|
|
10
|
-
authorize: (headers, key) => headers.set('x-goog-api-key', key),
|
|
11
|
-
},
|
|
12
|
-
deepseek: {
|
|
13
|
-
baseUrl: 'https://api.deepseek.com',
|
|
14
|
-
authorize: (headers, key) => headers.set('authorization', `Bearer ${key}`),
|
|
15
|
-
},
|
|
16
|
-
};
|
|
17
|
-
function providerKey(env, provider) {
|
|
1
|
+
import { AGENT_PROVIDERS, AGENT_PROVIDER_CONFIG, AGENT_PROVIDER_SECRETS } from '@hintergrund/runtime-contracts';
|
|
2
|
+
/** Presents a provider's key the way its API expects (`AGENT_PROVIDER_CONFIG[provider].auth`). */
|
|
3
|
+
export function authorizeProvider(headers, provider, key) {
|
|
4
|
+
const { auth } = AGENT_PROVIDER_CONFIG[provider];
|
|
5
|
+
headers.set(auth.header, 'bearer' in auth && auth.bearer ? `Bearer ${key}` : key);
|
|
6
|
+
}
|
|
7
|
+
export function providerKey(env, provider) {
|
|
18
8
|
const value = env[AGENT_PROVIDER_SECRETS[provider]];
|
|
19
9
|
if (typeof value !== 'string')
|
|
20
10
|
return undefined;
|
|
@@ -36,14 +26,19 @@ export async function proxyAgentRequest(c) {
|
|
|
36
26
|
const provider = activeAgentProvider(c.env);
|
|
37
27
|
if (!provider)
|
|
38
28
|
return c.json({ error: 'No AI provider is configured for this project.' }, 503);
|
|
39
|
-
const { baseUrl
|
|
29
|
+
const { baseUrl } = AGENT_PROVIDER_CONFIG[provider];
|
|
40
30
|
const headers = new Headers();
|
|
41
31
|
for (const name of ['content-type', 'accept']) {
|
|
42
32
|
const value = c.req.header(name);
|
|
43
33
|
if (value)
|
|
44
34
|
headers.set(name, value);
|
|
45
35
|
}
|
|
46
|
-
|
|
36
|
+
// Provider protocol headers the SDK sets (e.g. anthropic-version, anthropic-beta) travel with the request.
|
|
37
|
+
for (const [name, value] of c.req.raw.headers) {
|
|
38
|
+
if (name.startsWith('anthropic-') && name !== 'anthropic-dangerous-direct-browser-access')
|
|
39
|
+
headers.set(name, value);
|
|
40
|
+
}
|
|
41
|
+
authorizeProvider(headers, provider, providerKey(c.env, provider));
|
|
47
42
|
const { search } = new URL(c.req.url);
|
|
48
43
|
const upstream = await fetch(`${baseUrl}/${c.req.param('path')}${search}`, {
|
|
49
44
|
method: c.req.method,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"github-secrets.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/github-secrets.handler.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"github-secrets.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/github-secrets.handler.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAEpC,OAAO,EAAsB,KAAK,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAC5E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AA2C9C,wBAAsB,iBAAiB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAI9E;AAED,wBAAsB,kBAAkB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAuB/E;AAED,wBAAsB,kBAAkB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAe/E;AAED,YAAY,EAAE,YAAY,EAAE,CAAC"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { AGENT_PROVIDERS, AGENT_PROVIDER_SECRETS } from '@hintergrund/runtime-contracts';
|
|
1
2
|
import { getGitHubConfig } from '../../../lib/config';
|
|
2
3
|
import { createGitHubClient } from '../../../lib/github';
|
|
3
4
|
import { checkIntegrationKey, INTEGRATION_SECRETS } from '../../../lib/integration-health';
|
|
@@ -13,15 +14,13 @@ const DEPLOYABLE_ACTION_SECRET_NAMES = new Set([
|
|
|
13
14
|
'STRIPE_WEBHOOK_SECRET',
|
|
14
15
|
'API_KEY',
|
|
15
16
|
'SETUP_TOKEN',
|
|
16
|
-
|
|
17
|
-
'DEEPSEEK_API_KEY',
|
|
17
|
+
...AGENT_PROVIDERS.map(provider => AGENT_PROVIDER_SECRETS[provider]),
|
|
18
18
|
]);
|
|
19
19
|
const DELETABLE_ACTION_SECRET_NAMES = new Set([
|
|
20
20
|
'STRIPE_SECRET_KEY',
|
|
21
21
|
'STRIPE_WEBHOOK_SECRET',
|
|
22
22
|
'API_KEY',
|
|
23
|
-
|
|
24
|
-
'DEEPSEEK_API_KEY',
|
|
23
|
+
...AGENT_PROVIDERS.map(provider => AGENT_PROVIDER_SECRETS[provider]),
|
|
25
24
|
]);
|
|
26
25
|
function secretName(value) {
|
|
27
26
|
const name = value.trim();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"setup.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/setup.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAWpC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAe9C,wBAAsB,kBAAkB,CAAC,GAAG,EAAE,OAAO,CAAC,UAAU,CAAC,EAAE,QAAQ,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAQtG;AAkBD,uFAAuF;AACvF,wBAAsB,YAAY,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAiBzE;AAED,wBAAsB,YAAY,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,
|
|
1
|
+
{"version":3,"file":"setup.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/setup.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAWpC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAe9C,wBAAsB,kBAAkB,CAAC,GAAG,EAAE,OAAO,CAAC,UAAU,CAAC,EAAE,QAAQ,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAQtG;AAkBD,uFAAuF;AACvF,wBAAsB,YAAY,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAiBzE;AAED,wBAAsB,YAAY,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAoMzE;AAED,wBAAsB,iBAAiB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC,CAE7E"}
|
|
@@ -7,7 +7,7 @@ import { DEFAULT_SHOP_SETTINGS } from '../../shop/handlers/products.handler';
|
|
|
7
7
|
import Stripe from 'stripe';
|
|
8
8
|
import { checkIntegrationKey } from '../../../lib/integration-health';
|
|
9
9
|
import { createId, ensureSchema, issueSessionForUser, nowSeconds } from '../../../lib/project-db';
|
|
10
|
-
import { AGENT_PROVIDERS, AGENT_PROVIDER_SECRETS, CONFIG_PATH as WEBSITE_CONFIG_PATH, SHOP_SETTINGS_PATH, EMAIL_SETTINGS_PATH,
|
|
10
|
+
import { AGENT_PROVIDERS, AGENT_PROVIDER_SECRETS, CONFIG_PATH as WEBSITE_CONFIG_PATH, SHOP_SETTINGS_PATH, EMAIL_SETTINGS_PATH, LIB_BARREL_PATH, PROJECT_FEATURES, PROJECT_FEATURE_LABELS, isDisabledFeaturePath, normalizeProjectConfig, normalizeProjectFeatures, pruneLibBarrel } from '@hintergrund/runtime-contracts';
|
|
11
11
|
import { validateI18nConfig, DEFAULT_I18N_CONFIG } from '@hintergrund/runtime-contracts';
|
|
12
12
|
import { translateWebsiteFiles } from '../../../lib/website-i18n';
|
|
13
13
|
async function hasAdminUsers(c) {
|
|
@@ -94,14 +94,6 @@ export async function setupProject(c) {
|
|
|
94
94
|
const paymentProvider = body.paymentProvider === 'stripe' || body.paymentProvider === 'bank_transfer' ? body.paymentProvider : null;
|
|
95
95
|
const agentProvider = typeof body.agentProvider === 'string' && AGENT_PROVIDERS.includes(body.agentProvider) ? body.agentProvider : null;
|
|
96
96
|
const agentProviderKey = typeof body.agentProviderKey === 'string' ? body.agentProviderKey.trim() : '';
|
|
97
|
-
const businessInput = body.business && typeof body.business === 'object' && !Array.isArray(body.business) ? body.business : {};
|
|
98
|
-
const business = {};
|
|
99
|
-
for (const key of ['companyName', 'street', 'postalCode', 'city', 'country', 'email', 'phone']) {
|
|
100
|
-
if (typeof businessInput[key] === 'string' && businessInput[key].trim())
|
|
101
|
-
business[key] = businessInput[key].trim().slice(0, 400);
|
|
102
|
-
}
|
|
103
|
-
if (features.sell && (!business.companyName || !business.street || !business.city))
|
|
104
|
-
return c.json({ error: 'Enter your business name and address for invoices.' }, 400);
|
|
105
97
|
if (!email)
|
|
106
98
|
return c.json({ error: 'An email address is required.' }, 400);
|
|
107
99
|
if (password.length < MIN_PASSWORD_LENGTH) {
|
|
@@ -243,18 +235,13 @@ export async function setupProject(c) {
|
|
|
243
235
|
fromName: typeof body.fromName === 'string' ? body.fromName.trim() : emailSettings.fromName,
|
|
244
236
|
replyTo: typeof body.replyTo === 'string' ? body.replyTo.trim() : emailSettings.replyTo,
|
|
245
237
|
}, 'Configure email sender settings [skip ci]', commitSha);
|
|
246
|
-
// The imprint and invoices name the same business: answered once, kept in one place.
|
|
247
|
-
if (Object.keys(business).length) {
|
|
248
|
-
const { data: legal, commitSha: legalCommitSha } = await readJsonConfig(client, LEGAL_CONTENT_PATH, {});
|
|
249
|
-
await stageConfig(client, LEGAL_CONTENT_PATH, { ...legal, ...business }, 'Record business details [skip ci]', legalCommitSha);
|
|
250
|
-
}
|
|
251
238
|
// Translate against the whole repository, not just what setup staged: every
|
|
252
239
|
// page needs the languages added here. Unchanged content
|
|
253
240
|
// keeps the translations the demo already made.
|
|
254
241
|
try {
|
|
255
242
|
staged.files = await translateWebsiteFiles(client, staged.files, {
|
|
256
|
-
|
|
257
|
-
|
|
243
|
+
// Only the key chosen at setup: no other provider may be picked up from the environment.
|
|
244
|
+
...c.env, ...Object.fromEntries(AGENT_PROVIDERS.map(provider => [AGENT_PROVIDER_SECRETS[provider], provider === agentProvider ? agentProviderKey : undefined])),
|
|
258
245
|
}, await client.getCommitSha(), staged.deletions);
|
|
259
246
|
}
|
|
260
247
|
catch (error) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Bindings } from '../../../index';
|
|
2
|
-
import { type
|
|
2
|
+
import { type EmailSettings, type EmailTemplates } from '@hintergrund/runtime-contracts';
|
|
3
3
|
export declare function readEmailSettings(env: Bindings): Promise<{
|
|
4
4
|
settings: EmailSettings;
|
|
5
5
|
}>;
|
|
@@ -7,6 +7,4 @@ export declare function readEmailSettings(env: Bindings): Promise<{
|
|
|
7
7
|
export declare function readEmailLayout(env: Bindings): Promise<string | undefined>;
|
|
8
8
|
/** The copy of every automated email; a missing message falls back to the default. */
|
|
9
9
|
export declare function readEmailTemplates(env: Bindings): Promise<EmailTemplates>;
|
|
10
|
-
/** The business behind the site, as the imprint shows it. */
|
|
11
|
-
export declare function readBusinessDetails(env: Bindings): Promise<BusinessDetails>;
|
|
12
10
|
//# sourceMappingURL=settings.handler.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"settings.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/handlers/settings.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAI/C,OAAO,
|
|
1
|
+
{"version":3,"file":"settings.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/handlers/settings.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAI/C,OAAO,EAAyF,KAAK,aAAa,EAAE,KAAK,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAEhL,wBAAsB,iBAAiB,CAAC,GAAG,EAAE,QAAQ;;GAGpD;AACD,iHAAiH;AACjH,wBAAsB,eAAe,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAIhF;AACD,sFAAsF;AACtF,wBAAsB,kBAAkB,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,cAAc,CAAC,CAG/E"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { getGitHubConfig } from '../../../lib/config';
|
|
2
2
|
import { createGitHubClient } from '../../../lib/github';
|
|
3
3
|
import { readJsonConfig } from '../../../lib/github-config';
|
|
4
|
-
import { EMAIL_LAYOUT_PATH, EMAIL_SETTINGS_PATH, EMAIL_TEMPLATES_PATH,
|
|
4
|
+
import { EMAIL_LAYOUT_PATH, EMAIL_SETTINGS_PATH, EMAIL_TEMPLATES_PATH, normalizeEmailTemplates } from '@hintergrund/runtime-contracts';
|
|
5
5
|
export async function readEmailSettings(env) {
|
|
6
6
|
const { data } = await readJsonConfig(createGitHubClient(getGitHubConfig(env)), EMAIL_SETTINGS_PATH, {});
|
|
7
7
|
return { settings: data };
|
|
@@ -18,8 +18,3 @@ export async function readEmailTemplates(env) {
|
|
|
18
18
|
const { data } = await readJsonConfig(createGitHubClient(getGitHubConfig(env)), EMAIL_TEMPLATES_PATH, {});
|
|
19
19
|
return normalizeEmailTemplates(data);
|
|
20
20
|
}
|
|
21
|
-
/** The business behind the site, as the imprint shows it. */
|
|
22
|
-
export async function readBusinessDetails(env) {
|
|
23
|
-
const { data } = await readJsonConfig(createGitHubClient(getGitHubConfig(env)), LEGAL_CONTENT_PATH, {});
|
|
24
|
-
return data;
|
|
25
|
-
}
|
package/dist/index.d.ts
CHANGED
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAK5B,OAAO,EAAE,YAAY,EAAiB,MAAM,YAAY,CAAC;AAGzD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAMrE,MAAM,MAAM,QAAQ,GAAG;IAEtB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,iFAAiF;IACjF,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,4EAA4E;IAC5E,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAG7B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAG1B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,2DAA2D;IAC3D,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,YAAY,CAAC,EAAE,QAAQ,CAAC;IAGxB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,qBAAqB,CAAC,EAAE,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAK5B,OAAO,EAAE,YAAY,EAAiB,MAAM,YAAY,CAAC;AAGzD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAMrE,MAAM,MAAM,QAAQ,GAAG;IAEtB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,iFAAiF;IACjF,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,4EAA4E;IAC5E,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAG7B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAG1B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,2DAA2D;IAC3D,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,YAAY,CAAC,EAAE,QAAQ,CAAC;IAGxB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAI/B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAG3B,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,EAAE,OAAO,CAAC;IAChB,UAAU,CAAC,EAAE,UAAU,CAAC;CACxB,CAAC;AAEF,MAAM,MAAM,SAAS,GAAG;IACvB,IAAI,CAAC,EAAE;QACN,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;QACrB,WAAW,CAAC,EAAE,cAAc,EAAE,CAAC;KAC/B,CAAC;CACF,CAAC;AAEF,MAAM,MAAM,OAAO,GAAG;IAAE,QAAQ,EAAE,QAAQ,CAAC;IAAC,SAAS,EAAE,SAAS,CAAA;CAAE,CAAC;AAEnE,wBAAgB,SAAS,yDAoGxB;AAED,iGAAiG;AACjG,wBAAgB,YAAY;;;2BAKG,mBAAmB,OAAO,QAAQ;EAEhE;AAGD,cAAc,gBAAgB,CAAC;AAC/B,cAAc,mBAAmB,CAAC;AAClC,cAAc,gBAAgB,CAAC"}
|
|
@@ -1,9 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
readonly google: "GEMINI_API_KEY";
|
|
5
|
-
readonly deepseek: "DEEPSEEK_API_KEY";
|
|
6
|
-
};
|
|
1
|
+
import { type AgentProviderName } from '@hintergrund/runtime-contracts';
|
|
2
|
+
/** Payment and mail keys, plus every AI provider in AGENT_PROVIDER_CONFIG. */
|
|
3
|
+
export declare const INTEGRATION_SECRETS: Record<'stripe' | 'plunk' | AgentProviderName, string>;
|
|
7
4
|
export type IntegrationProvider = keyof typeof INTEGRATION_SECRETS;
|
|
8
5
|
export interface IntegrationHealth {
|
|
9
6
|
status: 'healthy' | 'warning' | 'invalid' | 'unavailable' | 'missing';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integration-health.d.ts","sourceRoot":"","sources":["../../src/lib/integration-health.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,mBAAmB
|
|
1
|
+
{"version":3,"file":"integration-health.d.ts","sourceRoot":"","sources":["../../src/lib/integration-health.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiD,KAAK,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AAEvH,8EAA8E;AAC9E,eAAO,MAAM,mBAAmB,EAAE,MAAM,CAAC,QAAQ,GAAG,OAAO,GAAG,iBAAiB,EAAE,MAAM,CAEtF,CAAC;AACF,MAAM,MAAM,mBAAmB,GAAG,MAAM,OAAO,mBAAmB,CAAC;AACnE,MAAM,WAAW,iBAAiB;IACjC,MAAM,EAAE,SAAS,GAAG,SAAS,GAAG,SAAS,GAAG,aAAa,GAAG,SAAS,CAAC;IACtE,KAAK,EAAE,OAAO,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;CAChB;AACD,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,GAAG,KAAK,IAAI,mBAAmB,CAEjF;AAED;;GAEG;AACH,wBAAsB,mBAAmB,CAAC,QAAQ,EAAE,mBAAmB,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAwCnH"}
|
|
@@ -1,5 +1,8 @@
|
|
|
1
|
+
import { AGENT_PROVIDER_CONFIG, AGENT_PROVIDER_SECRETS } from '@hintergrund/runtime-contracts';
|
|
2
|
+
import { authorizeProvider } from '../api/cms/handlers/agent-provider.handler';
|
|
3
|
+
/** Payment and mail keys, plus every AI provider in AGENT_PROVIDER_CONFIG. */
|
|
1
4
|
export const INTEGRATION_SECRETS = {
|
|
2
|
-
stripe: 'STRIPE_SECRET_KEY', plunk: 'API_KEY',
|
|
5
|
+
stripe: 'STRIPE_SECRET_KEY', plunk: 'API_KEY', ...AGENT_PROVIDER_SECRETS,
|
|
3
6
|
};
|
|
4
7
|
export function isIntegrationProvider(value) {
|
|
5
8
|
return Object.prototype.hasOwnProperty.call(INTEGRATION_SECRETS, value);
|
|
@@ -13,15 +16,21 @@ export async function checkIntegrationKey(provider, rawKey) {
|
|
|
13
16
|
return { status: 'missing', valid: false, message: 'No key is configured.' };
|
|
14
17
|
if (key.length > 4096 || /[\r\n]/.test(key))
|
|
15
18
|
return { status: 'invalid', valid: false, message: 'Invalid API key format.' };
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
19
|
+
const ai = provider === 'stripe' || provider === 'plunk' ? null : AGENT_PROVIDER_CONFIG[provider];
|
|
20
|
+
const url = provider === 'stripe' ? 'https://api.stripe.com/v1/account'
|
|
21
|
+
: provider === 'plunk' ? 'https://next-api.useplunk.com/contacts?limit=1'
|
|
22
|
+
: `${ai.baseUrl}${ai.healthPath}`;
|
|
23
|
+
const headers = new Headers();
|
|
24
|
+
if (ai) {
|
|
25
|
+
authorizeProvider(headers, provider, key);
|
|
26
|
+
if (provider === 'anthropic')
|
|
27
|
+
headers.set('anthropic-version', '2023-06-01');
|
|
28
|
+
}
|
|
29
|
+
else
|
|
30
|
+
headers.set('Authorization', `Bearer ${key}`);
|
|
22
31
|
try {
|
|
23
|
-
const response = await fetch(
|
|
24
|
-
headers
|
|
32
|
+
const response = await fetch(url, {
|
|
33
|
+
headers,
|
|
25
34
|
signal: AbortSignal.timeout(10000), redirect: 'error',
|
|
26
35
|
});
|
|
27
36
|
if (!response.ok) {
|
package/dist/lib/invoice.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { generateInvoicePdf } from '@hintergrund/runtime-contracts/invoice-pdf';
|
|
2
2
|
import { readInvoiceDesign, readDesignAsset } from './design';
|
|
3
|
-
import {
|
|
3
|
+
import { readShopSettings } from '../api/shop/handlers/products.handler';
|
|
4
4
|
export async function renderInvoice(env, data) {
|
|
5
|
-
const [invoiceDesign,
|
|
5
|
+
const [invoiceDesign, { settings }] = await Promise.all([readInvoiceDesign(env), readShopSettings(env)]);
|
|
6
6
|
const [logo, font] = await Promise.all([invoiceDesign.logoPath, invoiceDesign.fontPath].map(path => path ? readDesignAsset(env, path) : undefined));
|
|
7
|
-
return generateInvoicePdf(
|
|
7
|
+
return generateInvoicePdf(settings.seller ?? {}, data, invoiceDesign, { logo, font });
|
|
8
8
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"website-i18n.d.ts","sourceRoot":"","sources":["../../src/lib/website-i18n.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"website-i18n.d.ts","sourceRoot":"","sources":["../../src/lib/website-i18n.ts"],"names":[],"mappings":"AAAA,OAAO,EAAuN,KAAK,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AAC9R,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,KAAK,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAIxD,wIAAwI;AACxI,KAAK,OAAO,GAAG,kBAAkB,GAAG;IAAE,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,cAAc,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAiGhG,2FAA2F;AAC3F,wBAAsB,YAAY,CAAC,GAAG,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAkBxF;AAED,wBAAsB,SAAS,CAAC,GAAG,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAGhH;AAED,0KAA0K;AAC1K,wBAAsB,gBAAgB,CAAC,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,SAAS,CAAC,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC,CAazG;AAED,uEAAuE;AACvE,wBAAsB,qBAAqB,CAAC,MAAM,EAAE,YAAY,EAAE,KAAK,EAAE,SAAS,EAAE,EAAE,GAAG,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,GAAE,MAAM,EAAO,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC,CAUrK"}
|
package/dist/lib/website-i18n.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { CONFIG_PATH, CONTENT_CONFIG_PATH, I18N_RUNTIME_PATH, applyContentTranslations, collectMessages, isTranslatableContentPath, normalizeProjectConfig, translationStatus } from '@hintergrund/runtime-contracts';
|
|
1
|
+
import { AGENT_PROVIDER_CONFIG, CONFIG_PATH, CONTENT_CONFIG_PATH, I18N_RUNTIME_PATH, applyContentTranslations, collectMessages, isTranslatableContentPath, normalizeProjectConfig, translationStatus } from '@hintergrund/runtime-contracts';
|
|
2
2
|
import { stringifyJsonc } from './jsonc';
|
|
3
|
-
import { activeAgentProvider } from '../api/cms/handlers/agent-provider.handler';
|
|
3
|
+
import { activeAgentProvider, authorizeProvider, providerKey } from '../api/cms/handlers/agent-provider.handler';
|
|
4
4
|
/** Content of the repository, with the size limit the translator supports. */
|
|
5
5
|
function collect(files, sourceLanguage) {
|
|
6
6
|
const messages = collectMessages(files.values(), sourceLanguage);
|
|
@@ -24,6 +24,59 @@ function protect(text) {
|
|
|
24
24
|
return value.replace(/⟦(\d+)⟧/g, (_, index) => tokens[Number(index)]);
|
|
25
25
|
} };
|
|
26
26
|
}
|
|
27
|
+
/** The shape every provider must answer translation with. */
|
|
28
|
+
const TRANSLATIONS_SCHEMA = { type: 'object', properties: { translations: { type: 'array', items: { type: 'string' } } }, required: ['translations'], additionalProperties: false };
|
|
29
|
+
/**
|
|
30
|
+
* One request that must come back as `{ translations: string[] }`, forced the strictest way each
|
|
31
|
+
* provider allows. Model, endpoint and wire format (`translationApi`) come from AGENT_PROVIDER_CONFIG.
|
|
32
|
+
*/
|
|
33
|
+
async function completeJson(env, provider, instruction, input) {
|
|
34
|
+
const { baseUrl, translationModel: model, translationApi } = AGENT_PROVIDER_CONFIG[provider];
|
|
35
|
+
const headers = new Headers({ 'Content-Type': 'application/json' });
|
|
36
|
+
authorizeProvider(headers, provider, providerKey(env, provider));
|
|
37
|
+
const request = (path, body) => fetch(`${baseUrl}${path}`, { method: 'POST', headers, body: JSON.stringify(body), signal: AbortSignal.timeout(60_000) })
|
|
38
|
+
.then(async (response) => {
|
|
39
|
+
if (!response.ok)
|
|
40
|
+
throw new Error(`Translation provider returned ${response.status}.`);
|
|
41
|
+
return response.json();
|
|
42
|
+
});
|
|
43
|
+
switch (translationApi) {
|
|
44
|
+
case 'gemini': {
|
|
45
|
+
// The schema forces exactly { translations: string[] }.
|
|
46
|
+
const data = await request(`/models/${model}:generateContent`, {
|
|
47
|
+
systemInstruction: { parts: [{ text: instruction }] }, contents: [{ role: 'user', parts: [{ text: input }] }],
|
|
48
|
+
generationConfig: { responseMimeType: 'application/json', responseSchema: { type: 'OBJECT', properties: { translations: { type: 'ARRAY', items: { type: 'STRING' } } }, required: ['translations'] }, temperature: 0.2, maxOutputTokens: 8192, thinkingConfig: { thinkingLevel: 'low' } },
|
|
49
|
+
});
|
|
50
|
+
return JSON.parse(data.candidates?.[0]?.content?.parts?.map((part) => part.text ?? '').join('') || '{}');
|
|
51
|
+
}
|
|
52
|
+
case 'chat-json-schema': {
|
|
53
|
+
// Strict structured output: the reply must match the schema.
|
|
54
|
+
const data = await request('/chat/completions', {
|
|
55
|
+
model, messages: [{ role: 'system', content: instruction }, { role: 'user', content: input }],
|
|
56
|
+
response_format: { type: 'json_schema', json_schema: { name: 'translations', strict: true, schema: TRANSLATIONS_SCHEMA } }, max_completion_tokens: 8192,
|
|
57
|
+
});
|
|
58
|
+
return JSON.parse(data.choices?.[0]?.message?.content || '{}');
|
|
59
|
+
}
|
|
60
|
+
case 'anthropic-tool': {
|
|
61
|
+
// A forced tool call: the tool input is the answer, validated against the schema.
|
|
62
|
+
headers.set('anthropic-version', '2023-06-01');
|
|
63
|
+
const data = await request('/v1/messages', {
|
|
64
|
+
model, max_tokens: 8192, temperature: 0.2, system: instruction, messages: [{ role: 'user', content: input }],
|
|
65
|
+
tools: [{ name: 'submit_translations', description: 'Submit the translations, in input order.', input_schema: TRANSLATIONS_SCHEMA }],
|
|
66
|
+
tool_choice: { type: 'tool', name: 'submit_translations' },
|
|
67
|
+
});
|
|
68
|
+
return data.content?.find((block) => block.type === 'tool_use')?.input ?? {};
|
|
69
|
+
}
|
|
70
|
+
case 'chat-json-object': {
|
|
71
|
+
// JSON mode guarantees valid JSON only; the shape is checked by the caller.
|
|
72
|
+
const data = await request('/chat/completions', {
|
|
73
|
+
model, messages: [{ role: 'system', content: instruction }, { role: 'user', content: input }],
|
|
74
|
+
response_format: { type: 'json_object' }, temperature: 0.2, max_tokens: 8192,
|
|
75
|
+
});
|
|
76
|
+
return JSON.parse(data.choices?.[0]?.message?.content || '{}');
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
27
80
|
async function translateBatch(env, messages) {
|
|
28
81
|
const provider = activeAgentProvider(env);
|
|
29
82
|
if (!provider)
|
|
@@ -34,22 +87,7 @@ async function translateBatch(env, messages) {
|
|
|
34
87
|
let lastError;
|
|
35
88
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
36
89
|
try {
|
|
37
|
-
const
|
|
38
|
-
const response = await fetch(google
|
|
39
|
-
? 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash-lite:generateContent'
|
|
40
|
-
: 'https://api.deepseek.com/chat/completions', {
|
|
41
|
-
method: 'POST', signal: AbortSignal.timeout(60_000),
|
|
42
|
-
headers: { 'Content-Type': 'application/json', ...(google ? { 'x-goog-api-key': env.GEMINI_API_KEY } : { Authorization: `Bearer ${env.DEEPSEEK_API_KEY}` }) },
|
|
43
|
-
body: JSON.stringify(google ? {
|
|
44
|
-
systemInstruction: { parts: [{ text: instruction }] }, contents: [{ role: 'user', parts: [{ text: input }] }],
|
|
45
|
-
generationConfig: { responseMimeType: 'application/json', temperature: 0.2, maxOutputTokens: 8192, thinkingConfig: { thinkingLevel: 'low' } },
|
|
46
|
-
} : { model: 'deepseek-flash', messages: [{ role: 'system', content: instruction }, { role: 'user', content: input }], response_format: { type: 'json_object' }, temperature: 0.2, max_tokens: 8192 }),
|
|
47
|
-
});
|
|
48
|
-
if (!response.ok)
|
|
49
|
-
throw new Error(`Translation provider returned ${response.status}.`);
|
|
50
|
-
const data = await response.json();
|
|
51
|
-
const text = google ? data.candidates?.[0]?.content?.parts?.map(part => part.text ?? '').join('') : data.choices?.[0]?.message?.content;
|
|
52
|
-
const result = JSON.parse(text ?? '{}');
|
|
90
|
+
const result = await completeJson(env, provider, instruction, input);
|
|
53
91
|
if (!Array.isArray(result.translations) || result.translations.length !== messages.length)
|
|
54
92
|
throw new Error('Translation provider returned an incomplete batch.');
|
|
55
93
|
return result.translations.map((value, index) => {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hintergrund/worker",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.18",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -13,6 +13,14 @@
|
|
|
13
13
|
"files": [
|
|
14
14
|
"dist"
|
|
15
15
|
],
|
|
16
|
+
"publishConfig": {
|
|
17
|
+
"access": "public"
|
|
18
|
+
},
|
|
19
|
+
"repository": {
|
|
20
|
+
"type": "git",
|
|
21
|
+
"url": "git+https://github.com/hintergrund-dev/hintergrund-mono.git",
|
|
22
|
+
"directory": "apps/hintergrund-cloud/packages/worker"
|
|
23
|
+
},
|
|
16
24
|
"devDependencies": {
|
|
17
25
|
"@cloudflare/workers-types": "^5.20260915.1",
|
|
18
26
|
"concurrently": "^9.2.1",
|
|
@@ -27,7 +35,7 @@
|
|
|
27
35
|
"postal-mime": "^3.0.0",
|
|
28
36
|
"stripe": "^17.5.0",
|
|
29
37
|
"tweetnacl": "^1.0.3",
|
|
30
|
-
"@hintergrund/runtime-contracts": "0.3.
|
|
38
|
+
"@hintergrund/runtime-contracts": "0.3.18"
|
|
31
39
|
},
|
|
32
40
|
"scripts": {
|
|
33
41
|
"build": "tsc",
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import { type Design, type InvoiceDesign, type BusinessDetails, type InvoiceData } from '@hintergrund/runtime-contracts';
|
|
2
|
-
export interface InvoiceAssets {
|
|
3
|
-
logo?: Uint8Array;
|
|
4
|
-
bodyFont?: Uint8Array;
|
|
5
|
-
displayFont?: Uint8Array;
|
|
6
|
-
}
|
|
7
|
-
/** Same deterministic renderer for preview, downloads and email attachments. */
|
|
8
|
-
export declare function generateInvoicePdf(business: BusinessDetails, data: InvoiceData, design: Design, invoiceDesign: InvoiceDesign, assets?: InvoiceAssets): Promise<Uint8Array>;
|
|
9
|
-
//# sourceMappingURL=invoice.handler.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"invoice.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/handlers/invoice.handler.ts"],"names":[],"mappings":"AAEA,OAAO,EAAyC,KAAK,MAAM,EAAE,KAAK,aAAa,EAAE,KAAK,eAAe,EAAE,KAAK,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAEhK,MAAM,WAAW,aAAa;IAAG,IAAI,CAAC,EAAE,UAAU,CAAC;IAAC,QAAQ,CAAC,EAAE,UAAU,CAAC;IAAC,WAAW,CAAC,EAAE,UAAU,CAAA;CAAE;AAErG,gFAAgF;AAChF,wBAAsB,kBAAkB,CAAC,QAAQ,EAAE,eAAe,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,GAAE,aAAkB,GAAG,OAAO,CAAC,UAAU,CAAC,CA8GpL"}
|
|
@@ -1,154 +0,0 @@
|
|
|
1
|
-
import { PDFDocument, StandardFonts, rgb } from 'pdf-lib';
|
|
2
|
-
import fontkit from '@pdf-lib/fontkit';
|
|
3
|
-
import { validateDesign, validateInvoiceDesign } from '@hintergrund/runtime-contracts';
|
|
4
|
-
/** Same deterministic renderer for preview, downloads and email attachments. */
|
|
5
|
-
export async function generateInvoicePdf(business, data, design, invoiceDesign, assets = {}) {
|
|
6
|
-
validateDesign(design);
|
|
7
|
-
validateInvoiceDesign(invoiceDesign);
|
|
8
|
-
const pdf = await PDFDocument.create();
|
|
9
|
-
pdf.registerFontkit(fontkit);
|
|
10
|
-
const standard = (name) => name === 'Georgia' ? StandardFonts.TimesRoman : name === 'Courier New' ? StandardFonts.Courier : StandardFonts.Helvetica;
|
|
11
|
-
// PDFs embed the TTF/OTF `embed` file, never the woff2 the site downloads.
|
|
12
|
-
if ((design.fonts.body.embed && !assets.bodyFont) || (design.fonts.headings.embed && !assets.displayFont))
|
|
13
|
-
throw new Error('Missing design font asset.');
|
|
14
|
-
const font = await pdf.embedFont(assets.bodyFont ?? standard(design.fonts.body.family), { subset: true });
|
|
15
|
-
const heading = await pdf.embedFont(assets.displayFont ?? standard(design.fonts.headings.family), { subset: true });
|
|
16
|
-
const color = (hex) => rgb(...[1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16) / 255));
|
|
17
|
-
const ink = color(design.colors.text), primary = color(design.colors.primary), muted = color(design.colors.muted);
|
|
18
|
-
const [width, height] = invoiceDesign.pageSize === 'A4' ? [595.28, 841.89] : [612, 792];
|
|
19
|
-
const margin = invoiceDesign.margin, size = invoiceDesign.fontSize, line = size * invoiceDesign.lineHeight;
|
|
20
|
-
const contentWidth = width - 2 * margin;
|
|
21
|
-
let page, y;
|
|
22
|
-
const wrap = (text, maxWidth, face = font, fontSize = size) => {
|
|
23
|
-
const lines = [];
|
|
24
|
-
for (const paragraph of String(text).replace(/\r/g, '').split('\n')) {
|
|
25
|
-
let current = '';
|
|
26
|
-
for (const word of paragraph.split(/\s+/)) {
|
|
27
|
-
const candidate = current ? `${current} ${word}` : word;
|
|
28
|
-
if (face.widthOfTextAtSize(candidate, fontSize) <= maxWidth) {
|
|
29
|
-
current = candidate;
|
|
30
|
-
continue;
|
|
31
|
-
}
|
|
32
|
-
if (current) {
|
|
33
|
-
lines.push(current);
|
|
34
|
-
current = '';
|
|
35
|
-
}
|
|
36
|
-
// Only split within a word when a single token cannot fit the column.
|
|
37
|
-
for (const char of word) {
|
|
38
|
-
if (current && face.widthOfTextAtSize(current + char, fontSize) > maxWidth) {
|
|
39
|
-
lines.push(current);
|
|
40
|
-
current = '';
|
|
41
|
-
}
|
|
42
|
-
current += char;
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
lines.push(current);
|
|
46
|
-
}
|
|
47
|
-
return lines;
|
|
48
|
-
};
|
|
49
|
-
const footerLines = wrap(invoiceDesign.footerText, contentWidth, font, 8);
|
|
50
|
-
const bottom = margin + footerLines.length * 11 + 22;
|
|
51
|
-
function newPage() {
|
|
52
|
-
page = pdf.addPage([width, height]);
|
|
53
|
-
page.drawRectangle({ x: 0, y: 0, width, height, color: color(design.colors.surface) });
|
|
54
|
-
y = height - margin;
|
|
55
|
-
}
|
|
56
|
-
function ensure(space) { if (y - space < bottom)
|
|
57
|
-
newPage(); }
|
|
58
|
-
function text(value, face = font, fontSize = size, tone = ink) {
|
|
59
|
-
for (const row of wrap(value, contentWidth, face, fontSize)) {
|
|
60
|
-
ensure(fontSize * invoiceDesign.lineHeight);
|
|
61
|
-
page.drawText(row, { x: margin, y: y - fontSize, size: fontSize, font: face, color: tone });
|
|
62
|
-
y -= fontSize * invoiceDesign.lineHeight;
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
newPage();
|
|
66
|
-
// The letterhead is chosen in invoice design, independent of the website.
|
|
67
|
-
if (invoiceDesign.logoPath && assets.logo) {
|
|
68
|
-
const image = /\.png$/i.test(invoiceDesign.logoPath) ? await pdf.embedPng(assets.logo) : await pdf.embedJpg(assets.logo);
|
|
69
|
-
const scale = Math.min(invoiceDesign.logoWidth / image.width, 64 / image.height);
|
|
70
|
-
const w = image.width * scale, h = image.height * scale;
|
|
71
|
-
const x = invoiceDesign.logoPosition === 'right' ? width - margin - w : invoiceDesign.logoPosition === 'center' ? (width - w) / 2 : margin;
|
|
72
|
-
page.drawImage(image, { x, y: y - h, width: w, height: h });
|
|
73
|
-
y -= h + line;
|
|
74
|
-
}
|
|
75
|
-
const locality = [business.postalCode, business.city].filter(Boolean).join(' ');
|
|
76
|
-
for (const value of [business.companyName, business.street, locality, business.country, business.email, business.phone, business.vatId && `VAT ID: ${business.vatId}`])
|
|
77
|
-
if (value)
|
|
78
|
-
text(value);
|
|
79
|
-
y -= line;
|
|
80
|
-
text('INVOICE', heading, invoiceDesign.titleSize, primary);
|
|
81
|
-
text(`Invoice: ${data.invoiceNumber}`);
|
|
82
|
-
text(`Date: ${data.invoiceDate}`);
|
|
83
|
-
if (data.dueDate)
|
|
84
|
-
text(`Due: ${data.dueDate}`);
|
|
85
|
-
y -= line;
|
|
86
|
-
text('Bill to', heading);
|
|
87
|
-
for (const value of [data.customerName, data.customerEmail, data.customerAddress])
|
|
88
|
-
if (value)
|
|
89
|
-
text(value);
|
|
90
|
-
y -= line;
|
|
91
|
-
const descriptionWidth = contentWidth * .45;
|
|
92
|
-
const qtyX = margin + contentWidth * .59, priceX = margin + contentWidth * .78, totalX = width - margin - 6;
|
|
93
|
-
function right(value, x, at) {
|
|
94
|
-
page.drawText(value, { x: x - font.widthOfTextAtSize(value, size), y: at, size, font, color: ink });
|
|
95
|
-
}
|
|
96
|
-
function tableHeader() {
|
|
97
|
-
ensure(line * 3);
|
|
98
|
-
page.drawRectangle({ x: margin, y: y - line - 10, width: contentWidth, height: line + 10, color: primary });
|
|
99
|
-
const headerColor = (() => { const c = design.colors.primary; const brightness = .299 * parseInt(c.slice(1, 3), 16) + .587 * parseInt(c.slice(3, 5), 16) + .114 * parseInt(c.slice(5, 7), 16); return brightness > 155 ? rgb(0, 0, 0) : rgb(1, 1, 1); })();
|
|
100
|
-
for (const [label, x] of [['Description', margin + 6], ['Qty', qtyX - 20], ['Price', priceX - 30], ['Total', totalX - 30]])
|
|
101
|
-
page.drawText(label, { x, y: y - size - 5, size, font, color: headerColor });
|
|
102
|
-
y -= line + 16;
|
|
103
|
-
}
|
|
104
|
-
const money = (amount) => new Intl.NumberFormat('en', { style: 'currency', currency: data.currency }).format(amount);
|
|
105
|
-
tableHeader();
|
|
106
|
-
for (const [index, item] of data.items.entries()) {
|
|
107
|
-
const lines = wrap(item.description, descriptionWidth - 12);
|
|
108
|
-
const rowHeight = lines.length * line + 6;
|
|
109
|
-
if (rowHeight < height - margin - bottom - line - 16 && y - rowHeight < bottom) {
|
|
110
|
-
newPage();
|
|
111
|
-
tableHeader();
|
|
112
|
-
}
|
|
113
|
-
for (let i = 0; i < lines.length; i++) {
|
|
114
|
-
if (y - line - 6 < bottom) {
|
|
115
|
-
newPage();
|
|
116
|
-
tableHeader();
|
|
117
|
-
}
|
|
118
|
-
if (invoiceDesign.tableStyle === 'striped' && index % 2 === 0)
|
|
119
|
-
page.drawRectangle({ x: margin, y: y - line, width: contentWidth, height: line, color: primary, opacity: .06 });
|
|
120
|
-
page.drawText(lines[i], { x: margin + 6, y: y - size, size, font, color: ink });
|
|
121
|
-
if (i === 0) {
|
|
122
|
-
right(String(item.quantity), qtyX, y - size);
|
|
123
|
-
right(money(item.unitPrice), priceX, y - size);
|
|
124
|
-
right(money(item.total), totalX, y - size);
|
|
125
|
-
}
|
|
126
|
-
y -= line;
|
|
127
|
-
}
|
|
128
|
-
y -= 6;
|
|
129
|
-
}
|
|
130
|
-
ensure(line * 5 + 16);
|
|
131
|
-
y -= 12;
|
|
132
|
-
page.drawLine({ start: { x: margin, y: y }, end: { x: width - margin, y: y }, color: muted, thickness: .5 });
|
|
133
|
-
y -= line;
|
|
134
|
-
// Display recorded monetary values, never recompute them using design/settings.
|
|
135
|
-
for (const [label, amount] of [['Subtotal', data.subtotal], ['Tax', data.tax], ['Total', data.total]]) {
|
|
136
|
-
if (amount === undefined)
|
|
137
|
-
continue;
|
|
138
|
-
text(`${label}: ${money(amount)}`);
|
|
139
|
-
}
|
|
140
|
-
if (data.paymentMethod) {
|
|
141
|
-
y -= line;
|
|
142
|
-
text(`Payment method: ${data.paymentMethod}`);
|
|
143
|
-
}
|
|
144
|
-
if (data.notes) {
|
|
145
|
-
y -= line;
|
|
146
|
-
text(data.notes);
|
|
147
|
-
}
|
|
148
|
-
for (const [index, p] of pdf.getPages().entries()) {
|
|
149
|
-
footerLines.forEach((row, i) => p.drawText(row, { x: margin, y: margin + (footerLines.length - i) * 11, size: 8, font, color: muted }));
|
|
150
|
-
p.drawText(`${index + 1} / ${pdf.getPageCount()}`, { x: width - margin - 35, y: margin - 10, size: 8, font, color: muted });
|
|
151
|
-
}
|
|
152
|
-
pdf.setTitle(`Invoice ${data.invoiceNumber}`);
|
|
153
|
-
return pdf.save();
|
|
154
|
-
}
|
package/dist/lib/brand.d.ts
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import type { Bindings } from '../index';
|
|
2
|
-
export declare function readDesign(env: Bindings): Promise<import("@hintergrund/runtime-contracts").Design>;
|
|
3
|
-
export declare function readInvoiceDesign(env: Bindings): Promise<import("@hintergrund/runtime-contracts").InvoiceDesign>;
|
|
4
|
-
export declare function readDesignAsset(env: Bindings, path: string): Promise<Uint8Array>;
|
|
5
|
-
export declare function base64(bytes: Uint8Array): string;
|
|
6
|
-
//# sourceMappingURL=brand.d.ts.map
|
package/dist/lib/brand.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"brand.d.ts","sourceRoot":"","sources":["../../src/lib/brand.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAKzC,wBAAsB,UAAU,CAAC,GAAG,EAAE,QAAQ,4DAK7C;AACD,wBAAsB,iBAAiB,CAAC,GAAG,EAAE,QAAQ,mEAIpD;AACD,wBAAsB,eAAe,CAAC,GAAG,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CAMtF;AACD,wBAAgB,MAAM,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAIhD"}
|
package/dist/lib/brand.js
DELETED
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import { DESIGN_PATH, validateDesign, INVOICE_DESIGN_PATH, DEFAULT_INVOICE_DESIGN, validateInvoiceDesign, publicAssetPath } from '@hintergrund/runtime-contracts';
|
|
2
|
-
import { createGitHubClient } from './github';
|
|
3
|
-
import { getGitHubConfig } from './config';
|
|
4
|
-
import { readJsonConfig } from './github-config';
|
|
5
|
-
export async function readDesign(env) {
|
|
6
|
-
const github = createGitHubClient(getGitHubConfig(env));
|
|
7
|
-
const file = await github.readJsonFileIfExists(DESIGN_PATH);
|
|
8
|
-
if (!file)
|
|
9
|
-
throw new Error(`Missing ${DESIGN_PATH}. Every website template ships one.`);
|
|
10
|
-
return validateDesign(file.data);
|
|
11
|
-
}
|
|
12
|
-
export async function readInvoiceDesign(env) {
|
|
13
|
-
const github = createGitHubClient(getGitHubConfig(env));
|
|
14
|
-
const { data } = await readJsonConfig(github, INVOICE_DESIGN_PATH, DEFAULT_INVOICE_DESIGN);
|
|
15
|
-
return validateInvoiceDesign(data);
|
|
16
|
-
}
|
|
17
|
-
export async function readDesignAsset(env, path) {
|
|
18
|
-
publicAssetPath(path);
|
|
19
|
-
const file = await createGitHubClient(getGitHubConfig(env)).readFileBinary(path);
|
|
20
|
-
if (!file)
|
|
21
|
-
throw new Error(`Design asset not found: ${path}`);
|
|
22
|
-
if (file.content.length > 8 * 1024 * 1024)
|
|
23
|
-
throw new Error('Design asset exceeds 6 MB.');
|
|
24
|
-
return Uint8Array.from(atob(file.content), char => char.charCodeAt(0));
|
|
25
|
-
}
|
|
26
|
-
export function base64(bytes) {
|
|
27
|
-
let result = '';
|
|
28
|
-
for (let i = 0; i < bytes.length; i += 8192)
|
|
29
|
-
result += String.fromCharCode(...bytes.subarray(i, i + 8192));
|
|
30
|
-
return btoa(result);
|
|
31
|
-
}
|