@htlkg/data 0.0.15 → 0.0.16

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.
@@ -1,8 +1,9 @@
1
- import { Brand, Account, User, Product, ProductInstance } from '@htlkg/core/types';
1
+ import { Brand, Account, User, Product, ProductInstance, SystemSettings } from '@htlkg/core/types';
2
2
  import { AstroGlobal } from 'astro';
3
3
  import { generateServerClient } from '../client/index.js';
4
4
  import 'aws-amplify/data';
5
5
  import 'aws-amplify';
6
+ import '../server/index.js';
6
7
  import 'aws-amplify/api/internals';
7
8
 
8
9
  /**
@@ -460,4 +461,55 @@ declare function executeServerQuery<TSchema extends Record<string, unknown>, TRe
460
461
  */
461
462
  declare function executePublicQuery<TSchema extends Record<string, unknown>, TResult>(astro: AstroGlobal, runWithAmplifyServerContext: RunWithAmplifyServerContext, operation: (client: ReturnType<typeof generateServerClient<TSchema>>) => Promise<TResult>): Promise<TResult>;
462
463
 
463
- export { executePublicQuery, executeServerQuery, getAccount, getAccountWithBrands, getBrand, getBrandWithProducts, getProduct, getProductInstance, getUser, getUserByCognitoId, getUserByEmail, listAccounts, listActiveBrands, listActiveProducts, listActiveUsers, listBrands, listBrandsByAccount, listEnabledProductInstancesByBrand, listProductInstancesByAccount, listProductInstancesByBrand, listProducts, listUsers, listUsersByAccount };
464
+ /**
465
+ * SystemSettings Query Functions
466
+ *
467
+ * Provides query functions for fetching system settings from the GraphQL API.
468
+ */
469
+
470
+ /** Default retention days if no settings exist */
471
+ declare const DEFAULT_SOFT_DELETE_RETENTION_DAYS = 30;
472
+ /** The key used for global system settings */
473
+ declare const SYSTEM_SETTINGS_KEY = "GLOBAL";
474
+ /**
475
+ * Get system settings
476
+ *
477
+ * @example
478
+ * ```typescript
479
+ * import { getSystemSettings } from '@htlkg/data/queries';
480
+ * import { generateClient } from '@htlkg/data/client';
481
+ *
482
+ * const client = generateClient<Schema>();
483
+ * const settings = await getSystemSettings(client);
484
+ * ```
485
+ */
486
+ declare function getSystemSettings<TClient = any>(client: TClient): Promise<SystemSettings | null>;
487
+ /**
488
+ * Get the soft delete retention days from system settings
489
+ * Returns the default (30 days) if settings don't exist
490
+ *
491
+ * @example
492
+ * ```typescript
493
+ * import { getSoftDeleteRetentionDays } from '@htlkg/data/queries';
494
+ * import { generateClient } from '@htlkg/data/client';
495
+ *
496
+ * const client = generateClient<Schema>();
497
+ * const days = await getSoftDeleteRetentionDays(client);
498
+ * ```
499
+ */
500
+ declare function getSoftDeleteRetentionDays<TClient = any>(client: TClient): Promise<number>;
501
+ /**
502
+ * Check if a soft-deleted item can still be restored based on retention period
503
+ *
504
+ * @param deletedAt - The ISO date string when the item was deleted
505
+ * @param retentionDays - Number of days items can be restored
506
+ * @returns Object with canRestore flag and daysRemaining/daysExpired
507
+ */
508
+ declare function checkRestoreEligibility(deletedAt: string | undefined | null, retentionDays: number): {
509
+ canRestore: boolean;
510
+ daysRemaining: number;
511
+ daysExpired: number;
512
+ expiresAt: Date | null;
513
+ };
514
+
515
+ export { DEFAULT_SOFT_DELETE_RETENTION_DAYS, SYSTEM_SETTINGS_KEY, checkRestoreEligibility, executePublicQuery, executeServerQuery, getAccount, getAccountWithBrands, getBrand, getBrandWithProducts, getProduct, getProductInstance, getSoftDeleteRetentionDays, getSystemSettings, getUser, getUserByCognitoId, getUserByEmail, listAccounts, listActiveBrands, listActiveProducts, listActiveUsers, listBrands, listBrandsByAccount, listEnabledProductInstancesByBrand, listProductInstancesByAccount, listProductInstancesByBrand, listProducts, listUsers, listUsersByAccount };
@@ -329,6 +329,7 @@ async function listEnabledProductInstancesByBrand(client, brandId, options) {
329
329
 
330
330
  // src/client/index.ts
331
331
  import { generateClient as generateDataClient } from "aws-amplify/data";
332
+ import { Amplify } from "aws-amplify";
332
333
 
333
334
  // src/client/server.ts
334
335
  import {
@@ -339,7 +340,7 @@ import { createRunWithAmplifyServerContext, createLogger } from "@htlkg/core/amp
339
340
  var log = createLogger("server-client");
340
341
 
341
342
  // src/client/index.ts
342
- function generateServerClient(options) {
343
+ function generateServerClient(_options) {
343
344
  const client = generateDataClient();
344
345
  return client;
345
346
  }
@@ -371,7 +372,63 @@ async function executePublicQuery(astro, runWithAmplifyServerContext, operation)
371
372
  });
372
373
  return result;
373
374
  }
375
+
376
+ // src/queries/systemSettings.ts
377
+ var DEFAULT_SOFT_DELETE_RETENTION_DAYS = 30;
378
+ var SYSTEM_SETTINGS_KEY = "GLOBAL";
379
+ async function getSystemSettings(client) {
380
+ try {
381
+ const { data, errors } = await client.models.SystemSettings.get({
382
+ key: SYSTEM_SETTINGS_KEY
383
+ });
384
+ if (errors) {
385
+ console.error("[getSystemSettings] GraphQL errors:", errors);
386
+ return null;
387
+ }
388
+ return data;
389
+ } catch (error) {
390
+ console.error("[getSystemSettings] Error fetching system settings:", error);
391
+ throw error;
392
+ }
393
+ }
394
+ async function getSoftDeleteRetentionDays(client) {
395
+ const settings = await getSystemSettings(client);
396
+ return settings?.softDeleteRetentionDays ?? DEFAULT_SOFT_DELETE_RETENTION_DAYS;
397
+ }
398
+ function checkRestoreEligibility(deletedAt, retentionDays) {
399
+ if (!deletedAt) {
400
+ return {
401
+ canRestore: false,
402
+ daysRemaining: 0,
403
+ daysExpired: 0,
404
+ expiresAt: null
405
+ };
406
+ }
407
+ const deletedDate = new Date(deletedAt);
408
+ const expiresAt = new Date(deletedDate);
409
+ expiresAt.setDate(expiresAt.getDate() + retentionDays);
410
+ const now = /* @__PURE__ */ new Date();
411
+ const msRemaining = expiresAt.getTime() - now.getTime();
412
+ const daysRemaining = Math.ceil(msRemaining / (1e3 * 60 * 60 * 24));
413
+ if (daysRemaining <= 0) {
414
+ return {
415
+ canRestore: false,
416
+ daysRemaining: 0,
417
+ daysExpired: Math.abs(daysRemaining),
418
+ expiresAt
419
+ };
420
+ }
421
+ return {
422
+ canRestore: true,
423
+ daysRemaining,
424
+ daysExpired: 0,
425
+ expiresAt
426
+ };
427
+ }
374
428
  export {
429
+ DEFAULT_SOFT_DELETE_RETENTION_DAYS,
430
+ SYSTEM_SETTINGS_KEY,
431
+ checkRestoreEligibility,
375
432
  executePublicQuery,
376
433
  executeServerQuery,
377
434
  getAccount,
@@ -380,6 +437,8 @@ export {
380
437
  getBrandWithProducts,
381
438
  getProduct,
382
439
  getProductInstance,
440
+ getSoftDeleteRetentionDays,
441
+ getSystemSettings,
383
442
  getUser,
384
443
  getUserByCognitoId,
385
444
  getUserByEmail,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/queries/brands.ts","../../src/queries/accounts.ts","../../src/queries/users.ts","../../src/queries/products.ts","../../src/client/index.ts","../../src/client/server.ts","../../src/queries/server-helpers.ts"],"sourcesContent":["/**\n * Brand Query Functions\n *\n * Provides query functions for fetching brand data from the GraphQL API.\n */\n\nimport type { Brand } from \"@htlkg/core/types\";\n\n/**\n * Get a single brand by ID\n *\n * @example\n * ```typescript\n * import { getBrand } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const brand = await getBrand(client, 'brand-123');\n * ```\n */\nexport async function getBrand<TClient = any>(\n\tclient: TClient,\n\tid: string,\n): Promise<Brand | null> {\n\ttry {\n\t\tconst { data, errors } = await (client as any).models.Brand.get({ id });\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[getBrand] GraphQL errors:\", errors);\n\t\t\treturn null;\n\t\t}\n\n\t\treturn data as Brand;\n\t} catch (error) {\n\t\tconsole.error(\"[getBrand] Error fetching brand:\", error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * List all brands with optional filtering\n *\n * @example\n * ```typescript\n * import { listBrands } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const brands = await listBrands(client, {\n * filter: { status: { eq: 'active' } }\n * });\n * ```\n */\nexport async function listBrands<TClient = any>(\n\tclient: TClient,\n\toptions?: {\n\t\tfilter?: any;\n\t\tlimit?: number;\n\t\tnextToken?: string;\n\t},\n): Promise<{ items: Brand[]; nextToken?: string }> {\n\ttry {\n\t\tconst { data, errors, nextToken } = await (client as any).models.Brand.list(\n\t\t\toptions,\n\t\t);\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[listBrands] GraphQL errors:\", errors);\n\t\t\treturn { items: [], nextToken: undefined };\n\t\t}\n\n\t\treturn {\n\t\t\titems: (data || []) as Brand[],\n\t\t\tnextToken,\n\t\t};\n\t} catch (error) {\n\t\tconsole.error(\"[listBrands] Error fetching brands:\", error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * Get a brand with its product instances\n *\n * @example\n * ```typescript\n * import { getBrandWithProducts } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const brand = await getBrandWithProducts(client, 'brand-123');\n * ```\n */\nexport async function getBrandWithProducts<TClient = any>(\n\tclient: TClient,\n\tid: string,\n): Promise<Brand | null> {\n\ttry {\n\t\tconst { data, errors } = await (client as any).models.Brand.get(\n\t\t\t{ id },\n\t\t\t{\n\t\t\t\tselectionSet: [\n\t\t\t\t\t\"id\",\n\t\t\t\t\t\"name\",\n\t\t\t\t\t\"accountId\",\n\t\t\t\t\t\"logo\",\n\t\t\t\t\t\"timezone\",\n\t\t\t\t\t\"status\",\n\t\t\t\t\t\"settings\",\n\t\t\t\t\t\"productInstances.*\",\n\t\t\t\t],\n\t\t\t},\n\t\t);\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[getBrandWithProducts] GraphQL errors:\", errors);\n\t\t\treturn null;\n\t\t}\n\n\t\treturn data as Brand;\n\t} catch (error) {\n\t\tconsole.error(\"[getBrandWithProducts] Error fetching brand:\", error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * List brands by account ID\n *\n * @example\n * ```typescript\n * import { listBrandsByAccount } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const brands = await listBrandsByAccount(client, 'account-123');\n * ```\n */\nexport async function listBrandsByAccount<TClient = any>(\n\tclient: TClient,\n\taccountId: string,\n\toptions?: {\n\t\tlimit?: number;\n\t\tnextToken?: string;\n\t},\n): Promise<{ items: Brand[]; nextToken?: string }> {\n\treturn listBrands(client, {\n\t\tfilter: { accountId: { eq: accountId } },\n\t\t...options,\n\t});\n}\n\n/**\n * List active brands\n *\n * @example\n * ```typescript\n * import { listActiveBrands } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const brands = await listActiveBrands(client);\n * ```\n */\nexport async function listActiveBrands<TClient = any>(\n\tclient: TClient,\n\toptions?: {\n\t\tlimit?: number;\n\t\tnextToken?: string;\n\t},\n): Promise<{ items: Brand[]; nextToken?: string }> {\n\treturn listBrands(client, {\n\t\tfilter: { status: { eq: \"active\" } },\n\t\t...options,\n\t});\n}\n","/**\n * Account Query Functions\n *\n * Provides query functions for fetching account data from the GraphQL API.\n */\n\nimport type { Account } from \"@htlkg/core/types\";\n\n/**\n * Get a single account by ID\n *\n * @example\n * ```typescript\n * import { getAccount } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const account = await getAccount(client, 'account-123');\n * ```\n */\nexport async function getAccount<TClient = any>(\n\tclient: TClient,\n\tid: string,\n): Promise<Account | null> {\n\ttry {\n\t\tconst { data, errors } = await (client as any).models.Account.get({ id });\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[getAccount] GraphQL errors:\", errors);\n\t\t\treturn null;\n\t\t}\n\n\t\treturn data as Account;\n\t} catch (error) {\n\t\tconsole.error(\"[getAccount] Error fetching account:\", error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * List all accounts with optional filtering\n *\n * @example\n * ```typescript\n * import { listAccounts } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const accounts = await listAccounts(client);\n * ```\n */\nexport async function listAccounts<TClient = any>(\n\tclient: TClient,\n\toptions?: {\n\t\tfilter?: any;\n\t\tlimit?: number;\n\t\tnextToken?: string;\n\t},\n): Promise<{ items: Account[]; nextToken?: string }> {\n\ttry {\n\t\tconst { data, errors, nextToken } = await (\n\t\t\tclient as any\n\t\t).models.Account.list(options);\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[listAccounts] GraphQL errors:\", errors);\n\t\t\treturn { items: [], nextToken: undefined };\n\t\t}\n\n\t\treturn {\n\t\t\titems: (data || []) as Account[],\n\t\t\tnextToken,\n\t\t};\n\t} catch (error) {\n\t\tconsole.error(\"[listAccounts] Error fetching accounts:\", error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * Get an account with its brands\n *\n * @example\n * ```typescript\n * import { getAccountWithBrands } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const account = await getAccountWithBrands(client, 'account-123');\n * ```\n */\nexport async function getAccountWithBrands<TClient = any>(\n\tclient: TClient,\n\tid: string,\n): Promise<Account | null> {\n\ttry {\n\t\tconst { data, errors } = await (client as any).models.Account.get(\n\t\t\t{ id },\n\t\t\t{\n\t\t\t\tselectionSet: [\n\t\t\t\t\t\"id\",\n\t\t\t\t\t\"name\",\n\t\t\t\t\t\"logo\",\n\t\t\t\t\t\"subscription\",\n\t\t\t\t\t\"settings\",\n\t\t\t\t\t\"brands.*\",\n\t\t\t\t],\n\t\t\t},\n\t\t);\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[getAccountWithBrands] GraphQL errors:\", errors);\n\t\t\treturn null;\n\t\t}\n\n\t\treturn data as Account;\n\t} catch (error) {\n\t\tconsole.error(\"[getAccountWithBrands] Error fetching account:\", error);\n\t\tthrow error;\n\t}\n}\n","/**\n * User Query Functions\n *\n * Provides query functions for fetching user data from the GraphQL API.\n */\n\nimport type { User } from \"@htlkg/core/types\";\n\n/**\n * Get a single user by ID\n *\n * @example\n * ```typescript\n * import { getUser } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const user = await getUser(client, 'user-123');\n * ```\n */\nexport async function getUser<TClient = any>(\n\tclient: TClient,\n\tid: string,\n): Promise<User | null> {\n\ttry {\n\t\tconst { data, errors } = await (client as any).models.User.get({ id });\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[getUser] GraphQL errors:\", errors);\n\t\t\treturn null;\n\t\t}\n\n\t\treturn data as User;\n\t} catch (error) {\n\t\tconsole.error(\"[getUser] Error fetching user:\", error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * Get a user by Cognito ID\n *\n * @example\n * ```typescript\n * import { getUserByCognitoId } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const user = await getUserByCognitoId(client, 'cognito-id-123');\n * ```\n */\nexport async function getUserByCognitoId<TClient = any>(\n\tclient: TClient,\n\tcognitoId: string,\n): Promise<User | null> {\n\ttry {\n\t\tconst { data, errors } = await (client as any).models.User.list({\n\t\t\tfilter: { cognitoId: { eq: cognitoId } },\n\t\t\tlimit: 1,\n\t\t});\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[getUserByCognitoId] GraphQL errors:\", errors);\n\t\t\treturn null;\n\t\t}\n\n\t\treturn data?.[0] as User | null;\n\t} catch (error) {\n\t\tconsole.error(\"[getUserByCognitoId] Error fetching user:\", error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * Get a user by email\n *\n * @example\n * ```typescript\n * import { getUserByEmail } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const user = await getUserByEmail(client, 'user@example.com');\n * ```\n */\nexport async function getUserByEmail<TClient = any>(\n\tclient: TClient,\n\temail: string,\n): Promise<User | null> {\n\ttry {\n\t\tconst { data, errors } = await (client as any).models.User.list({\n\t\t\tfilter: { email: { eq: email } },\n\t\t\tlimit: 1,\n\t\t});\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[getUserByEmail] GraphQL errors:\", errors);\n\t\t\treturn null;\n\t\t}\n\n\t\treturn data?.[0] as User | null;\n\t} catch (error) {\n\t\tconsole.error(\"[getUserByEmail] Error fetching user:\", error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * List all users with optional filtering\n *\n * @example\n * ```typescript\n * import { listUsers } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const users = await listUsers(client, {\n * filter: { status: { eq: 'active' } }\n * });\n * ```\n */\nexport async function listUsers<TClient = any>(\n\tclient: TClient,\n\toptions?: {\n\t\tfilter?: any;\n\t\tlimit?: number;\n\t\tnextToken?: string;\n\t},\n): Promise<{ items: User[]; nextToken?: string }> {\n\ttry {\n\t\tconst { data, errors, nextToken } = await (client as any).models.User.list(\n\t\t\toptions,\n\t\t);\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[listUsers] GraphQL errors:\", errors);\n\t\t\treturn { items: [], nextToken: undefined };\n\t\t}\n\n\t\treturn {\n\t\t\titems: (data || []) as User[],\n\t\t\tnextToken,\n\t\t};\n\t} catch (error) {\n\t\tconsole.error(\"[listUsers] Error fetching users:\", error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * List users by account ID\n *\n * @example\n * ```typescript\n * import { listUsersByAccount } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const users = await listUsersByAccount(client, 'account-123');\n * ```\n */\nexport async function listUsersByAccount<TClient = any>(\n\tclient: TClient,\n\taccountId: string,\n\toptions?: {\n\t\tlimit?: number;\n\t\tnextToken?: string;\n\t},\n): Promise<{ items: User[]; nextToken?: string }> {\n\treturn listUsers(client, {\n\t\tfilter: { accountId: { eq: accountId } },\n\t\t...options,\n\t});\n}\n\n/**\n * List active users\n *\n * @example\n * ```typescript\n * import { listActiveUsers } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const users = await listActiveUsers(client);\n * ```\n */\nexport async function listActiveUsers<TClient = any>(\n\tclient: TClient,\n\toptions?: {\n\t\tlimit?: number;\n\t\tnextToken?: string;\n\t},\n): Promise<{ items: User[]; nextToken?: string }> {\n\treturn listUsers(client, {\n\t\tfilter: { status: { eq: \"active\" } },\n\t\t...options,\n\t});\n}\n","/**\n * Product Query Functions\n *\n * Provides query functions for fetching product and product instance data from the GraphQL API.\n */\n\nimport type { Product, ProductInstance } from \"@htlkg/core/types\";\n\n/**\n * Get a single product by ID\n *\n * @example\n * ```typescript\n * import { getProduct } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const product = await getProduct(client, 'product-123');\n * ```\n */\nexport async function getProduct<TClient = any>(\n\tclient: TClient,\n\tid: string,\n): Promise<Product | null> {\n\ttry {\n\t\tconst { data, errors } = await (client as any).models.Product.get({ id });\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[getProduct] GraphQL errors:\", errors);\n\t\t\treturn null;\n\t\t}\n\n\t\treturn data as Product;\n\t} catch (error) {\n\t\tconsole.error(\"[getProduct] Error fetching product:\", error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * List all products with optional filtering\n *\n * @example\n * ```typescript\n * import { listProducts } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const products = await listProducts(client, {\n * filter: { isActive: { eq: true } }\n * });\n * ```\n */\nexport async function listProducts<TClient = any>(\n\tclient: TClient,\n\toptions?: {\n\t\tfilter?: any;\n\t\tlimit?: number;\n\t\tnextToken?: string;\n\t},\n): Promise<{ items: Product[]; nextToken?: string }> {\n\ttry {\n\t\tconst { data, errors, nextToken } = await (\n\t\t\tclient as any\n\t\t).models.Product.list(options);\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[listProducts] GraphQL errors:\", errors);\n\t\t\treturn { items: [], nextToken: undefined };\n\t\t}\n\n\t\treturn {\n\t\t\titems: (data || []) as Product[],\n\t\t\tnextToken,\n\t\t};\n\t} catch (error) {\n\t\tconsole.error(\"[listProducts] Error fetching products:\", error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * List active products\n *\n * @example\n * ```typescript\n * import { listActiveProducts } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const products = await listActiveProducts(client);\n * ```\n */\nexport async function listActiveProducts<TClient = any>(\n\tclient: TClient,\n\toptions?: {\n\t\tlimit?: number;\n\t\tnextToken?: string;\n\t},\n): Promise<{ items: Product[]; nextToken?: string }> {\n\treturn listProducts(client, {\n\t\tfilter: { isActive: { eq: true } },\n\t\t...options,\n\t});\n}\n\n/**\n * Get a single product instance by ID\n *\n * @example\n * ```typescript\n * import { getProductInstance } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const instance = await getProductInstance(client, 'instance-123');\n * ```\n */\nexport async function getProductInstance<TClient = any>(\n\tclient: TClient,\n\tid: string,\n): Promise<ProductInstance | null> {\n\ttry {\n\t\tconst { data, errors } = await (client as any).models.ProductInstance.get({\n\t\t\tid,\n\t\t});\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[getProductInstance] GraphQL errors:\", errors);\n\t\t\treturn null;\n\t\t}\n\n\t\treturn data as ProductInstance;\n\t} catch (error) {\n\t\tconsole.error(\"[getProductInstance] Error fetching product instance:\", error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * List product instances by brand ID\n *\n * @example\n * ```typescript\n * import { listProductInstancesByBrand } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const instances = await listProductInstancesByBrand(client, 'brand-123');\n * ```\n */\nexport async function listProductInstancesByBrand<TClient = any>(\n\tclient: TClient,\n\tbrandId: string,\n\toptions?: {\n\t\tlimit?: number;\n\t\tnextToken?: string;\n\t},\n): Promise<{ items: ProductInstance[]; nextToken?: string }> {\n\ttry {\n\t\tconst { data, errors, nextToken } = await (\n\t\t\tclient as any\n\t\t).models.ProductInstance.list({\n\t\t\tfilter: { brandId: { eq: brandId } },\n\t\t\t...options,\n\t\t});\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[listProductInstancesByBrand] GraphQL errors:\", errors);\n\t\t\treturn { items: [], nextToken: undefined };\n\t\t}\n\n\t\treturn {\n\t\t\titems: (data || []) as ProductInstance[],\n\t\t\tnextToken,\n\t\t};\n\t} catch (error) {\n\t\tconsole.error(\n\t\t\t\"[listProductInstancesByBrand] Error fetching product instances:\",\n\t\t\terror,\n\t\t);\n\t\tthrow error;\n\t}\n}\n\n/**\n * List product instances by account ID\n *\n * @example\n * ```typescript\n * import { listProductInstancesByAccount } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const instances = await listProductInstancesByAccount(client, 'account-123');\n * ```\n */\nexport async function listProductInstancesByAccount<TClient = any>(\n\tclient: TClient,\n\taccountId: string,\n\toptions?: {\n\t\tlimit?: number;\n\t\tnextToken?: string;\n\t},\n): Promise<{ items: ProductInstance[]; nextToken?: string }> {\n\ttry {\n\t\tconst { data, errors, nextToken } = await (\n\t\t\tclient as any\n\t\t).models.ProductInstance.list({\n\t\t\tfilter: { accountId: { eq: accountId } },\n\t\t\t...options,\n\t\t});\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[listProductInstancesByAccount] GraphQL errors:\", errors);\n\t\t\treturn { items: [], nextToken: undefined };\n\t\t}\n\n\t\treturn {\n\t\t\titems: (data || []) as ProductInstance[],\n\t\t\tnextToken,\n\t\t};\n\t} catch (error) {\n\t\tconsole.error(\n\t\t\t\"[listProductInstancesByAccount] Error fetching product instances:\",\n\t\t\terror,\n\t\t);\n\t\tthrow error;\n\t}\n}\n\n/**\n * List enabled product instances by brand ID\n *\n * @example\n * ```typescript\n * import { listEnabledProductInstancesByBrand } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const instances = await listEnabledProductInstancesByBrand(client, 'brand-123');\n * ```\n */\nexport async function listEnabledProductInstancesByBrand<TClient = any>(\n\tclient: TClient,\n\tbrandId: string,\n\toptions?: {\n\t\tlimit?: number;\n\t\tnextToken?: string;\n\t},\n): Promise<{ items: ProductInstance[]; nextToken?: string }> {\n\ttry {\n\t\tconst { data, errors, nextToken } = await (\n\t\t\tclient as any\n\t\t).models.ProductInstance.list({\n\t\t\tfilter: {\n\t\t\t\tbrandId: { eq: brandId },\n\t\t\t\tenabled: { eq: true },\n\t\t\t},\n\t\t\t...options,\n\t\t});\n\n\t\tif (errors) {\n\t\t\tconsole.error(\n\t\t\t\t\"[listEnabledProductInstancesByBrand] GraphQL errors:\",\n\t\t\t\terrors,\n\t\t\t);\n\t\t\treturn { items: [], nextToken: undefined };\n\t\t}\n\n\t\treturn {\n\t\t\titems: (data || []) as ProductInstance[],\n\t\t\tnextToken,\n\t\t};\n\t} catch (error) {\n\t\tconsole.error(\n\t\t\t\"[listEnabledProductInstancesByBrand] Error fetching product instances:\",\n\t\t\terror,\n\t\t);\n\t\tthrow error;\n\t}\n}\n","/**\n * GraphQL Client for @htlkg/data\n *\n * Provides both client-side and server-side GraphQL capabilities using AWS Amplify Data.\n * The server-side functions use the Amplify Astro adapter for proper SSR support.\n */\n\nimport { generateClient as generateDataClient } from \"aws-amplify/data\";\nimport type { ResourcesConfig } from \"aws-amplify\";\n\n// Re-export server-side client generation\nexport { generateServerClientUsingCookies } from \"./server\";\n\n// Singleton client instance for client-side fetching\nlet sharedClientInstance: any = null;\n\n/**\n * Get or create the shared GraphQL client instance (singleton pattern)\n * Use this for client-side fetching to avoid creating multiple client instances.\n *\n * @example\n * ```typescript\n * const client = getSharedClient<Schema>();\n * const { data } = await client.models.Account.list();\n * ```\n */\nexport function getSharedClient<\n\tTSchema extends Record<string, unknown> = Record<string, unknown>,\n>(): ReturnType<typeof generateDataClient<TSchema>> {\n\tif (!sharedClientInstance) {\n\t\tsharedClientInstance = generateDataClient<TSchema>();\n\t}\n\treturn sharedClientInstance;\n}\n\n/**\n * Reset the shared client instance (useful for testing or auth state changes)\n */\nexport function resetSharedClient(): void {\n\tsharedClientInstance = null;\n}\n\n/**\n * Generate a client-side GraphQL client for use in Vue components and browser contexts\n * This is SSR-safe and should be called within a component's setup function or after hydration\n *\n * @example\n * ```typescript\n * import type { Schema } from '@backend/data/resource';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const { data: brands } = await client.models.Brand.list();\n * ```\n */\nexport function generateClient<\n\tTSchema extends Record<string, unknown> = Record<string, unknown>,\n>(): ReturnType<typeof generateDataClient<TSchema>> {\n\treturn generateDataClient<TSchema>();\n}\n\n/**\n * Configuration for Amplify (matches amplify_outputs.json format)\n */\nexport type AstroAmplifyConfig = ResourcesConfig;\n\n/**\n * Authentication mode for server-side GraphQL client\n */\nexport type ServerAuthMode = 'userPool' | 'apiKey';\n\n/**\n * Options for generating a server-side GraphQL client\n */\nexport interface GenerateServerClientOptions {\n\t/** Authentication mode - 'userPool' (default) uses JWT from cookies, 'apiKey' uses API key */\n\tauthMode?: ServerAuthMode;\n}\n\n/**\n * Generate a server-side GraphQL client for use within runWithAmplifyServerContext\n * \n * This function creates a GraphQL client that can be used for server-side data fetching in Astro.\n * It MUST be called within runWithAmplifyServerContext to access JWT tokens from cookies.\n * \n * The client supports two authentication modes:\n * - 'userPool' (default): Uses JWT tokens from cookies (requires runWithAmplifyServerContext)\n * - 'apiKey': Uses API key for public/unauthenticated requests\n *\n * **Important**: \n * - Amplify.configure() must be called once at app startup (e.g., in amplify-server.ts)\n * - This function must be called INSIDE the operation function of runWithAmplifyServerContext\n * - The context automatically provides the token provider that reads JWT tokens from cookies\n *\n * @example\n * ```typescript\n * // In your Astro page\n * import type { Schema } from '../amplify/data/resource';\n * import { generateServerClient } from '@htlkg/data/client';\n * import { createRunWithAmplifyServerContext } from '@htlkg/core/amplify-astro-adapter';\n * import outputs from '../amplify_outputs.json';\n *\n * const runWithAmplifyServerContext = createRunWithAmplifyServerContext({ config: outputs });\n *\n * // Fetch data with authentication\n * const result = await runWithAmplifyServerContext({\n * astroServerContext: {\n * cookies: Astro.cookies,\n * request: Astro.request\n * },\n * operation: async (contextSpec) => {\n * // Generate client INSIDE the operation\n * const client = generateServerClient<Schema>({ authMode: 'userPool' });\n * return await client.models.User.list();\n * }\n * });\n * \n * const users = result.data || [];\n * ```\n * \n * @example Using API key for public data\n * ```typescript\n * const result = await runWithAmplifyServerContext({\n * astroServerContext: {\n * cookies: Astro.cookies,\n * request: Astro.request\n * },\n * operation: async (contextSpec) => {\n * const client = generateServerClient<Schema>({ authMode: 'apiKey' });\n * return await client.models.Brand.list();\n * }\n * });\n * ```\n */\nexport function generateServerClient<\n\tTSchema extends Record<string, unknown> = Record<string, unknown>,\n>(options?: GenerateServerClientOptions): ReturnType<typeof generateDataClient<TSchema>> {\n\t// Generate the client without authMode parameter\n\t// When called within runWithAmplifyServerContext, it will automatically use the token provider\n\t// from the context (which reads JWT tokens from cookies)\n\t// The authMode should be specified per-operation, not at client creation\n\tconst client = generateDataClient<TSchema>();\n\t\n\treturn client;\n}\n","/**\n * Server-side data client for Astro\n *\n * Provides a client generator similar to Next.js's generateServerClientUsingCookies\n * using generateClientWithAmplifyInstance for proper server context integration.\n */\n\nimport type { AstroGlobal } from \"astro\";\nimport type { ResourcesConfig } from \"aws-amplify\";\nimport {\n\tCommonPublicClientOptions,\n\tDefaultCommonClientOptions,\n\tV6ClientSSRCookies,\n\tgenerateClientWithAmplifyInstance,\n} from \"aws-amplify/api/internals\";\nimport { getAmplifyServerContext } from \"aws-amplify/adapter-core/internals\";\nimport { createRunWithAmplifyServerContext, createLogger } from \"@htlkg/core/amplify-astro-adapter\";\n\nconst log = createLogger('server-client');\n\ninterface AstroCookiesClientParams {\n\tcookies: AstroGlobal[\"cookies\"];\n\trequest: AstroGlobal[\"request\"];\n\tconfig: ResourcesConfig;\n}\n\n/**\n * Generates a server-side data client for Astro (matches Next.js implementation)\n *\n * This function creates a client that automatically wraps all operations in the Amplify server context,\n * ensuring that authentication tokens from cookies are properly used.\n *\n * @example\n * ```typescript\n * import type { Schema } from '../amplify/data/resource';\n * import { generateServerClientUsingCookies } from '@htlkg/data/client';\n * import { parseAmplifyConfig } from 'aws-amplify/utils';\n * import outputs from '../amplify_outputs.json';\n *\n * const amplifyConfig = parseAmplifyConfig(outputs);\n *\n * const client = generateServerClientUsingCookies<Schema>({\n * config: amplifyConfig,\n * cookies: Astro.cookies,\n * request: Astro.request,\n * });\n *\n * // Use the client directly - operations are automatically wrapped\n * const result = await client.models.User.list({\n * selectionSet: ['id', 'email'],\n * limit: 100,\n * });\n * ```\n */\nexport function generateServerClientUsingCookies<\n\tT extends Record<any, any> = never,\n\tOptions extends CommonPublicClientOptions &\n\t\tAstroCookiesClientParams = DefaultCommonClientOptions &\n\t\tAstroCookiesClientParams,\n>(options: Options): V6ClientSSRCookies<T, Options> {\n\tconst runWithAmplifyServerContext = createRunWithAmplifyServerContext({\n\t\tconfig: options.config,\n\t});\n\n\tconst resourcesConfig = options.config;\n\n\t// This function reference gets passed down to InternalGraphQLAPI.ts.graphql\n\t// where this._graphql is passed in as the `fn` argument\n\t// causing it to always get invoked inside `runWithAmplifyServerContext`\n\tconst getAmplify = (fn: (amplify: any) => Promise<any>) => {\n\t\treturn runWithAmplifyServerContext({\n\t\t\tastroServerContext: {\n\t\t\t\tcookies: options.cookies,\n\t\t\t\trequest: options.request,\n\t\t\t},\n\t\t\toperation: async (contextSpec: any) => {\n\t\t\t\tconst amplifyInstance = getAmplifyServerContext(contextSpec).amplify;\n\t\t\t\t\n\t\t\t\t// Debug logging (only when DEBUG=true)\n\t\t\t\ttry {\n\t\t\t\t\tconst config = amplifyInstance.getConfig();\n\t\t\t\t\tlog.debug('Amplify config from instance:', {\n\t\t\t\t\t\thasAPI: !!config.API,\n\t\t\t\t\t\thasGraphQL: !!config.API?.GraphQL,\n\t\t\t\t\t\tendpoint: config.API?.GraphQL?.endpoint,\n\t\t\t\t\t\tdefaultAuthMode: config.API?.GraphQL?.defaultAuthMode,\n\t\t\t\t\t\tregion: config.API?.GraphQL?.region,\n\t\t\t\t\t});\n\t\t\t\t\t\n\t\t\t\t\tconst session = await amplifyInstance.Auth.fetchAuthSession();\n\t\t\t\t\tlog.debug('Auth session:', {\n\t\t\t\t\t\thasTokens: !!session.tokens,\n\t\t\t\t\t\thasAccessToken: !!session.tokens?.accessToken,\n\t\t\t\t\t\thasIdToken: !!session.tokens?.idToken,\n\t\t\t\t\t\thasCredentials: !!session.credentials,\n\t\t\t\t\t});\n\t\t\t\t} catch (e: any) {\n\t\t\t\t\tlog.debug('Error fetching session:', e.message);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\treturn fn(amplifyInstance);\n\t\t\t},\n\t\t});\n\t};\n\n\tconst {\n\t\tcookies: _cookies,\n\t\trequest: _request,\n\t\tconfig: _config,\n\t\t...params\n\t} = options;\n\n\treturn generateClientWithAmplifyInstance<T, V6ClientSSRCookies<T, Options>>({\n\t\tamplify: getAmplify,\n\t\tconfig: resourcesConfig,\n\t\t...params,\n\t} as any);\n}\n","/**\n * Server-Side Query Helpers\n *\n * Convenience functions for executing server-side queries in Astro pages.\n * These helpers simplify the common pattern of using runWithAmplifyServerContext.\n */\n\nimport type { AstroGlobal } from \"astro\";\nimport { generateServerClient } from \"../client\";\n\n/**\n * Type for the runWithAmplifyServerContext function\n */\ntype RunWithAmplifyServerContext = (options: {\n\tastroServerContext: {\n\t\tcookies: AstroGlobal[\"cookies\"];\n\t\trequest: AstroGlobal[\"request\"];\n\t};\n\toperation: (contextSpec: unknown) => Promise<unknown>;\n}) => Promise<unknown>;\n\n/**\n * Helper to execute server-side queries in Astro pages\n *\n * This function wraps the common pattern of using runWithAmplifyServerContext\n * with generateServerClient, making it easier to fetch data server-side.\n *\n * **Note**: This requires `createRunWithAmplifyServerContext` from `@htlkg/core/amplify-astro-adapter`.\n * If you need more control, use the full pattern directly.\n *\n * @example\n * ```typescript\n * import type { Schema } from '../amplify/data/resource';\n * import { executeServerQuery } from '@htlkg/data/queries/server-helpers';\n * import { createRunWithAmplifyServerContext } from '@htlkg/core/amplify-astro-adapter';\n * import outputs from '../amplify_outputs.json';\n *\n * const runWithAmplifyServerContext = createRunWithAmplifyServerContext({ config: outputs });\n *\n * const users = await executeServerQuery<Schema>(\n * Astro,\n * runWithAmplifyServerContext,\n * async (client) => {\n * const result = await client.models.User.list();\n * return result.data || [];\n * }\n * );\n * ```\n */\nexport async function executeServerQuery<\n\tTSchema extends Record<string, unknown>,\n\tTResult,\n>(\n\tastro: AstroGlobal,\n\trunWithAmplifyServerContext: RunWithAmplifyServerContext,\n\toperation: (client: ReturnType<typeof generateServerClient<TSchema>>) => Promise<TResult>,\n): Promise<TResult> {\n\tconst result = await runWithAmplifyServerContext({\n\t\tastroServerContext: {\n\t\t\tcookies: astro.cookies,\n\t\t\trequest: astro.request,\n\t\t},\n\t\toperation: async (contextSpec: unknown) => {\n\t\t\tconst client = generateServerClient<TSchema>();\n\t\t\treturn await operation(client);\n\t\t},\n\t});\n\treturn result as TResult;\n}\n\n/**\n * Helper to execute server-side queries with API key authentication (public data)\n *\n * Use this for fetching public data that doesn't require user authentication.\n *\n * @example\n * ```typescript\n * import type { Schema } from '../amplify/data/resource';\n * import { executePublicQuery } from '@htlkg/data/queries/server-helpers';\n * import { createRunWithAmplifyServerContext } from '@htlkg/core/amplify-astro-adapter';\n * import outputs from '../amplify_outputs.json';\n *\n * const runWithAmplifyServerContext = createRunWithAmplifyServerContext({ config: outputs });\n *\n * const brands = await executePublicQuery<Schema>(\n * Astro,\n * runWithAmplifyServerContext,\n * async (client) => {\n * const result = await client.models.Brand.list();\n * return result.data || [];\n * }\n * );\n * ```\n */\nexport async function executePublicQuery<\n\tTSchema extends Record<string, unknown>,\n\tTResult,\n>(\n\tastro: AstroGlobal,\n\trunWithAmplifyServerContext: RunWithAmplifyServerContext,\n\toperation: (client: ReturnType<typeof generateServerClient<TSchema>>) => Promise<TResult>,\n): Promise<TResult> {\n\tconst result = await runWithAmplifyServerContext({\n\t\tastroServerContext: {\n\t\t\tcookies: astro.cookies,\n\t\t\trequest: astro.request,\n\t\t},\n\t\toperation: async (_contextSpec: unknown) => {\n\t\t\tconst client = generateServerClient<TSchema>({ authMode: \"apiKey\" });\n\t\t\treturn await operation(client);\n\t\t},\n\t});\n\treturn result as TResult;\n}\n"],"mappings":";AAoBA,eAAsB,SACrB,QACA,IACwB;AACxB,MAAI;AACH,UAAM,EAAE,MAAM,OAAO,IAAI,MAAO,OAAe,OAAO,MAAM,IAAI,EAAE,GAAG,CAAC;AAEtE,QAAI,QAAQ;AACX,cAAQ,MAAM,8BAA8B,MAAM;AAClD,aAAO;AAAA,IACR;AAEA,WAAO;AAAA,EACR,SAAS,OAAO;AACf,YAAQ,MAAM,oCAAoC,KAAK;AACvD,UAAM;AAAA,EACP;AACD;AAgBA,eAAsB,WACrB,QACA,SAKkD;AAClD,MAAI;AACH,UAAM,EAAE,MAAM,QAAQ,UAAU,IAAI,MAAO,OAAe,OAAO,MAAM;AAAA,MACtE;AAAA,IACD;AAEA,QAAI,QAAQ;AACX,cAAQ,MAAM,gCAAgC,MAAM;AACpD,aAAO,EAAE,OAAO,CAAC,GAAG,WAAW,OAAU;AAAA,IAC1C;AAEA,WAAO;AAAA,MACN,OAAQ,QAAQ,CAAC;AAAA,MACjB;AAAA,IACD;AAAA,EACD,SAAS,OAAO;AACf,YAAQ,MAAM,uCAAuC,KAAK;AAC1D,UAAM;AAAA,EACP;AACD;AAcA,eAAsB,qBACrB,QACA,IACwB;AACxB,MAAI;AACH,UAAM,EAAE,MAAM,OAAO,IAAI,MAAO,OAAe,OAAO,MAAM;AAAA,MAC3D,EAAE,GAAG;AAAA,MACL;AAAA,QACC,cAAc;AAAA,UACb;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,QACD;AAAA,MACD;AAAA,IACD;AAEA,QAA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E,IAAM,MAAM,aAAa,eAAe;;;ADoHjC,SAAS,qBAEd,SAAuF;AAKxF,QAAM,SAAS,mBAA4B;AAE3C,SAAO;AACR;;;AE/FA,eAAsB,mBAIrB,OACA,6BACA,WACmB;AACnB,QAAM,SAAS,MAAM,4BAA4B;AAAA,IAChD,oBAAoB;AAAA,MACnB,SAAS,MAAM;AAAA,MACf,SAAS,MAAM;AAAA,IAChB;AAAA,IACA,WAAW,OAAO,gBAAyB;AAC1C,YAAM,SAAS,qBAA8B;AAC7C,aAAO,MAAM,UAAU,MAAM;AAAA,IAC9B;AAAA,EACD,CAAC;AACD,SAAO;AACR;AA0BA,eAAsB,mBAIrB,OACA,6BACA,WACmB;AACnB,QAAM,SAAS,MAAM,4BAA4B;AAAA,IAChD,oBAAoB;AAAA,MACnB,SAAS,MAAM;AAAA,MACf,SAAS,MAAM;AAAA,IAChB;AAAA,IACA,WAAW,OAAO,iBAA0B;AAC3C,YAAM,SAAS,qBAA8B,EAAE,UAAU,SAAS,CAAC;AACnE,aAAO,MAAM,UAAU,MAAM;AAAA,IAC9B;AAAA,EACD,CAAC;AACD,SAAO;AACR;","names":[]}
1
+ {"version":3,"sources":["../../src/queries/brands.ts","../../src/queries/accounts.ts","../../src/queries/users.ts","../../src/queries/products.ts","../../src/client/index.ts","../../src/client/server.ts","../../src/queries/server-helpers.ts","../../src/queries/systemSettings.ts"],"sourcesContent":["/**\n * Brand Query Functions\n *\n * Provides query functions for fetching brand data from the GraphQL API.\n */\n\nimport type { Brand } from \"@htlkg/core/types\";\n\n/**\n * Get a single brand by ID\n *\n * @example\n * ```typescript\n * import { getBrand } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const brand = await getBrand(client, 'brand-123');\n * ```\n */\nexport async function getBrand<TClient = any>(\n\tclient: TClient,\n\tid: string,\n): Promise<Brand | null> {\n\ttry {\n\t\tconst { data, errors } = await (client as any).models.Brand.get({ id });\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[getBrand] GraphQL errors:\", errors);\n\t\t\treturn null;\n\t\t}\n\n\t\treturn data as Brand;\n\t} catch (error) {\n\t\tconsole.error(\"[getBrand] Error fetching brand:\", error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * List all brands with optional filtering\n *\n * @example\n * ```typescript\n * import { listBrands } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const brands = await listBrands(client, {\n * filter: { status: { eq: 'active' } }\n * });\n * ```\n */\nexport async function listBrands<TClient = any>(\n\tclient: TClient,\n\toptions?: {\n\t\tfilter?: any;\n\t\tlimit?: number;\n\t\tnextToken?: string;\n\t},\n): Promise<{ items: Brand[]; nextToken?: string }> {\n\ttry {\n\t\tconst { data, errors, nextToken } = await (client as any).models.Brand.list(\n\t\t\toptions,\n\t\t);\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[listBrands] GraphQL errors:\", errors);\n\t\t\treturn { items: [], nextToken: undefined };\n\t\t}\n\n\t\treturn {\n\t\t\titems: (data || []) as Brand[],\n\t\t\tnextToken,\n\t\t};\n\t} catch (error) {\n\t\tconsole.error(\"[listBrands] Error fetching brands:\", error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * Get a brand with its product instances\n *\n * @example\n * ```typescript\n * import { getBrandWithProducts } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const brand = await getBrandWithProducts(client, 'brand-123');\n * ```\n */\nexport async function getBrandWithProducts<TClient = any>(\n\tclient: TClient,\n\tid: string,\n): Promise<Brand | null> {\n\ttry {\n\t\tconst { data, errors } = await (client as any).models.Brand.get(\n\t\t\t{ id },\n\t\t\t{\n\t\t\t\tselectionSet: [\n\t\t\t\t\t\"id\",\n\t\t\t\t\t\"name\",\n\t\t\t\t\t\"accountId\",\n\t\t\t\t\t\"logo\",\n\t\t\t\t\t\"timezone\",\n\t\t\t\t\t\"status\",\n\t\t\t\t\t\"settings\",\n\t\t\t\t\t\"productInstances.*\",\n\t\t\t\t],\n\t\t\t},\n\t\t);\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[getBrandWithProducts] GraphQL errors:\", errors);\n\t\t\treturn null;\n\t\t}\n\n\t\treturn data as Brand;\n\t} catch (error) {\n\t\tconsole.error(\"[getBrandWithProducts] Error fetching brand:\", error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * List brands by account ID\n *\n * @example\n * ```typescript\n * import { listBrandsByAccount } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const brands = await listBrandsByAccount(client, 'account-123');\n * ```\n */\nexport async function listBrandsByAccount<TClient = any>(\n\tclient: TClient,\n\taccountId: string,\n\toptions?: {\n\t\tlimit?: number;\n\t\tnextToken?: string;\n\t},\n): Promise<{ items: Brand[]; nextToken?: string }> {\n\treturn listBrands(client, {\n\t\tfilter: { accountId: { eq: accountId } },\n\t\t...options,\n\t});\n}\n\n/**\n * List active brands\n *\n * @example\n * ```typescript\n * import { listActiveBrands } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const brands = await listActiveBrands(client);\n * ```\n */\nexport async function listActiveBrands<TClient = any>(\n\tclient: TClient,\n\toptions?: {\n\t\tlimit?: number;\n\t\tnextToken?: string;\n\t},\n): Promise<{ items: Brand[]; nextToken?: string }> {\n\treturn listBrands(client, {\n\t\tfilter: { status: { eq: \"active\" } },\n\t\t...options,\n\t});\n}\n","/**\n * Account Query Functions\n *\n * Provides query functions for fetching account data from the GraphQL API.\n */\n\nimport type { Account } from \"@htlkg/core/types\";\n\n/**\n * Get a single account by ID\n *\n * @example\n * ```typescript\n * import { getAccount } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const account = await getAccount(client, 'account-123');\n * ```\n */\nexport async function getAccount<TClient = any>(\n\tclient: TClient,\n\tid: string,\n): Promise<Account | null> {\n\ttry {\n\t\tconst { data, errors } = await (client as any).models.Account.get({ id });\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[getAccount] GraphQL errors:\", errors);\n\t\t\treturn null;\n\t\t}\n\n\t\treturn data as Account;\n\t} catch (error) {\n\t\tconsole.error(\"[getAccount] Error fetching account:\", error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * List all accounts with optional filtering\n *\n * @example\n * ```typescript\n * import { listAccounts } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const accounts = await listAccounts(client);\n * ```\n */\nexport async function listAccounts<TClient = any>(\n\tclient: TClient,\n\toptions?: {\n\t\tfilter?: any;\n\t\tlimit?: number;\n\t\tnextToken?: string;\n\t},\n): Promise<{ items: Account[]; nextToken?: string }> {\n\ttry {\n\t\tconst { data, errors, nextToken } = await (\n\t\t\tclient as any\n\t\t).models.Account.list(options);\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[listAccounts] GraphQL errors:\", errors);\n\t\t\treturn { items: [], nextToken: undefined };\n\t\t}\n\n\t\treturn {\n\t\t\titems: (data || []) as Account[],\n\t\t\tnextToken,\n\t\t};\n\t} catch (error) {\n\t\tconsole.error(\"[listAccounts] Error fetching accounts:\", error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * Get an account with its brands\n *\n * @example\n * ```typescript\n * import { getAccountWithBrands } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const account = await getAccountWithBrands(client, 'account-123');\n * ```\n */\nexport async function getAccountWithBrands<TClient = any>(\n\tclient: TClient,\n\tid: string,\n): Promise<Account | null> {\n\ttry {\n\t\tconst { data, errors } = await (client as any).models.Account.get(\n\t\t\t{ id },\n\t\t\t{\n\t\t\t\tselectionSet: [\n\t\t\t\t\t\"id\",\n\t\t\t\t\t\"name\",\n\t\t\t\t\t\"logo\",\n\t\t\t\t\t\"subscription\",\n\t\t\t\t\t\"settings\",\n\t\t\t\t\t\"brands.*\",\n\t\t\t\t],\n\t\t\t},\n\t\t);\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[getAccountWithBrands] GraphQL errors:\", errors);\n\t\t\treturn null;\n\t\t}\n\n\t\treturn data as Account;\n\t} catch (error) {\n\t\tconsole.error(\"[getAccountWithBrands] Error fetching account:\", error);\n\t\tthrow error;\n\t}\n}\n","/**\n * User Query Functions\n *\n * Provides query functions for fetching user data from the GraphQL API.\n */\n\nimport type { User } from \"@htlkg/core/types\";\n\n/**\n * Get a single user by ID\n *\n * @example\n * ```typescript\n * import { getUser } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const user = await getUser(client, 'user-123');\n * ```\n */\nexport async function getUser<TClient = any>(\n\tclient: TClient,\n\tid: string,\n): Promise<User | null> {\n\ttry {\n\t\tconst { data, errors } = await (client as any).models.User.get({ id });\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[getUser] GraphQL errors:\", errors);\n\t\t\treturn null;\n\t\t}\n\n\t\treturn data as User;\n\t} catch (error) {\n\t\tconsole.error(\"[getUser] Error fetching user:\", error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * Get a user by Cognito ID\n *\n * @example\n * ```typescript\n * import { getUserByCognitoId } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const user = await getUserByCognitoId(client, 'cognito-id-123');\n * ```\n */\nexport async function getUserByCognitoId<TClient = any>(\n\tclient: TClient,\n\tcognitoId: string,\n): Promise<User | null> {\n\ttry {\n\t\tconst { data, errors } = await (client as any).models.User.list({\n\t\t\tfilter: { cognitoId: { eq: cognitoId } },\n\t\t\tlimit: 1,\n\t\t});\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[getUserByCognitoId] GraphQL errors:\", errors);\n\t\t\treturn null;\n\t\t}\n\n\t\treturn data?.[0] as User | null;\n\t} catch (error) {\n\t\tconsole.error(\"[getUserByCognitoId] Error fetching user:\", error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * Get a user by email\n *\n * @example\n * ```typescript\n * import { getUserByEmail } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const user = await getUserByEmail(client, 'user@example.com');\n * ```\n */\nexport async function getUserByEmail<TClient = any>(\n\tclient: TClient,\n\temail: string,\n): Promise<User | null> {\n\ttry {\n\t\tconst { data, errors } = await (client as any).models.User.list({\n\t\t\tfilter: { email: { eq: email } },\n\t\t\tlimit: 1,\n\t\t});\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[getUserByEmail] GraphQL errors:\", errors);\n\t\t\treturn null;\n\t\t}\n\n\t\treturn data?.[0] as User | null;\n\t} catch (error) {\n\t\tconsole.error(\"[getUserByEmail] Error fetching user:\", error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * List all users with optional filtering\n *\n * @example\n * ```typescript\n * import { listUsers } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const users = await listUsers(client, {\n * filter: { status: { eq: 'active' } }\n * });\n * ```\n */\nexport async function listUsers<TClient = any>(\n\tclient: TClient,\n\toptions?: {\n\t\tfilter?: any;\n\t\tlimit?: number;\n\t\tnextToken?: string;\n\t},\n): Promise<{ items: User[]; nextToken?: string }> {\n\ttry {\n\t\tconst { data, errors, nextToken } = await (client as any).models.User.list(\n\t\t\toptions,\n\t\t);\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[listUsers] GraphQL errors:\", errors);\n\t\t\treturn { items: [], nextToken: undefined };\n\t\t}\n\n\t\treturn {\n\t\t\titems: (data || []) as User[],\n\t\t\tnextToken,\n\t\t};\n\t} catch (error) {\n\t\tconsole.error(\"[listUsers] Error fetching users:\", error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * List users by account ID\n *\n * @example\n * ```typescript\n * import { listUsersByAccount } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const users = await listUsersByAccount(client, 'account-123');\n * ```\n */\nexport async function listUsersByAccount<TClient = any>(\n\tclient: TClient,\n\taccountId: string,\n\toptions?: {\n\t\tlimit?: number;\n\t\tnextToken?: string;\n\t},\n): Promise<{ items: User[]; nextToken?: string }> {\n\treturn listUsers(client, {\n\t\tfilter: { accountId: { eq: accountId } },\n\t\t...options,\n\t});\n}\n\n/**\n * List active users\n *\n * @example\n * ```typescript\n * import { listActiveUsers } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const users = await listActiveUsers(client);\n * ```\n */\nexport async function listActiveUsers<TClient = any>(\n\tclient: TClient,\n\toptions?: {\n\t\tlimit?: number;\n\t\tnextToken?: string;\n\t},\n): Promise<{ items: User[]; nextToken?: string }> {\n\treturn listUsers(client, {\n\t\tfilter: { status: { eq: \"active\" } },\n\t\t...options,\n\t});\n}\n","/**\n * Product Query Functions\n *\n * Provides query functions for fetching product and product instance data from the GraphQL API.\n */\n\nimport type { Product, ProductInstance } from \"@htlkg/core/types\";\n\n/**\n * Get a single product by ID\n *\n * @example\n * ```typescript\n * import { getProduct } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const product = await getProduct(client, 'product-123');\n * ```\n */\nexport async function getProduct<TClient = any>(\n\tclient: TClient,\n\tid: string,\n): Promise<Product | null> {\n\ttry {\n\t\tconst { data, errors } = await (client as any).models.Product.get({ id });\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[getProduct] GraphQL errors:\", errors);\n\t\t\treturn null;\n\t\t}\n\n\t\treturn data as Product;\n\t} catch (error) {\n\t\tconsole.error(\"[getProduct] Error fetching product:\", error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * List all products with optional filtering\n *\n * @example\n * ```typescript\n * import { listProducts } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const products = await listProducts(client, {\n * filter: { isActive: { eq: true } }\n * });\n * ```\n */\nexport async function listProducts<TClient = any>(\n\tclient: TClient,\n\toptions?: {\n\t\tfilter?: any;\n\t\tlimit?: number;\n\t\tnextToken?: string;\n\t},\n): Promise<{ items: Product[]; nextToken?: string }> {\n\ttry {\n\t\tconst { data, errors, nextToken } = await (\n\t\t\tclient as any\n\t\t).models.Product.list(options);\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[listProducts] GraphQL errors:\", errors);\n\t\t\treturn { items: [], nextToken: undefined };\n\t\t}\n\n\t\treturn {\n\t\t\titems: (data || []) as Product[],\n\t\t\tnextToken,\n\t\t};\n\t} catch (error) {\n\t\tconsole.error(\"[listProducts] Error fetching products:\", error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * List active products\n *\n * @example\n * ```typescript\n * import { listActiveProducts } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const products = await listActiveProducts(client);\n * ```\n */\nexport async function listActiveProducts<TClient = any>(\n\tclient: TClient,\n\toptions?: {\n\t\tlimit?: number;\n\t\tnextToken?: string;\n\t},\n): Promise<{ items: Product[]; nextToken?: string }> {\n\treturn listProducts(client, {\n\t\tfilter: { isActive: { eq: true } },\n\t\t...options,\n\t});\n}\n\n/**\n * Get a single product instance by ID\n *\n * @example\n * ```typescript\n * import { getProductInstance } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const instance = await getProductInstance(client, 'instance-123');\n * ```\n */\nexport async function getProductInstance<TClient = any>(\n\tclient: TClient,\n\tid: string,\n): Promise<ProductInstance | null> {\n\ttry {\n\t\tconst { data, errors } = await (client as any).models.ProductInstance.get({\n\t\t\tid,\n\t\t});\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[getProductInstance] GraphQL errors:\", errors);\n\t\t\treturn null;\n\t\t}\n\n\t\treturn data as ProductInstance;\n\t} catch (error) {\n\t\tconsole.error(\"[getProductInstance] Error fetching product instance:\", error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * List product instances by brand ID\n *\n * @example\n * ```typescript\n * import { listProductInstancesByBrand } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const instances = await listProductInstancesByBrand(client, 'brand-123');\n * ```\n */\nexport async function listProductInstancesByBrand<TClient = any>(\n\tclient: TClient,\n\tbrandId: string,\n\toptions?: {\n\t\tlimit?: number;\n\t\tnextToken?: string;\n\t},\n): Promise<{ items: ProductInstance[]; nextToken?: string }> {\n\ttry {\n\t\tconst { data, errors, nextToken } = await (\n\t\t\tclient as any\n\t\t).models.ProductInstance.list({\n\t\t\tfilter: { brandId: { eq: brandId } },\n\t\t\t...options,\n\t\t});\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[listProductInstancesByBrand] GraphQL errors:\", errors);\n\t\t\treturn { items: [], nextToken: undefined };\n\t\t}\n\n\t\treturn {\n\t\t\titems: (data || []) as ProductInstance[],\n\t\t\tnextToken,\n\t\t};\n\t} catch (error) {\n\t\tconsole.error(\n\t\t\t\"[listProductInstancesByBrand] Error fetching product instances:\",\n\t\t\terror,\n\t\t);\n\t\tthrow error;\n\t}\n}\n\n/**\n * List product instances by account ID\n *\n * @example\n * ```typescript\n * import { listProductInstancesByAccount } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const instances = await listProductInstancesByAccount(client, 'account-123');\n * ```\n */\nexport async function listProductInstancesByAccount<TClient = any>(\n\tclient: TClient,\n\taccountId: string,\n\toptions?: {\n\t\tlimit?: number;\n\t\tnextToken?: string;\n\t},\n): Promise<{ items: ProductInstance[]; nextToken?: string }> {\n\ttry {\n\t\tconst { data, errors, nextToken } = await (\n\t\t\tclient as any\n\t\t).models.ProductInstance.list({\n\t\t\tfilter: { accountId: { eq: accountId } },\n\t\t\t...options,\n\t\t});\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[listProductInstancesByAccount] GraphQL errors:\", errors);\n\t\t\treturn { items: [], nextToken: undefined };\n\t\t}\n\n\t\treturn {\n\t\t\titems: (data || []) as ProductInstance[],\n\t\t\tnextToken,\n\t\t};\n\t} catch (error) {\n\t\tconsole.error(\n\t\t\t\"[listProductInstancesByAccount] Error fetching product instances:\",\n\t\t\terror,\n\t\t);\n\t\tthrow error;\n\t}\n}\n\n/**\n * List enabled product instances by brand ID\n *\n * @example\n * ```typescript\n * import { listEnabledProductInstancesByBrand } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const instances = await listEnabledProductInstancesByBrand(client, 'brand-123');\n * ```\n */\nexport async function listEnabledProductInstancesByBrand<TClient = any>(\n\tclient: TClient,\n\tbrandId: string,\n\toptions?: {\n\t\tlimit?: number;\n\t\tnextToken?: string;\n\t},\n): Promise<{ items: ProductInstance[]; nextToken?: string }> {\n\ttry {\n\t\tconst { data, errors, nextToken } = await (\n\t\t\tclient as any\n\t\t).models.ProductInstance.list({\n\t\t\tfilter: {\n\t\t\t\tbrandId: { eq: brandId },\n\t\t\t\tenabled: { eq: true },\n\t\t\t},\n\t\t\t...options,\n\t\t});\n\n\t\tif (errors) {\n\t\t\tconsole.error(\n\t\t\t\t\"[listEnabledProductInstancesByBrand] GraphQL errors:\",\n\t\t\t\terrors,\n\t\t\t);\n\t\t\treturn { items: [], nextToken: undefined };\n\t\t}\n\n\t\treturn {\n\t\t\titems: (data || []) as ProductInstance[],\n\t\t\tnextToken,\n\t\t};\n\t} catch (error) {\n\t\tconsole.error(\n\t\t\t\"[listEnabledProductInstancesByBrand] Error fetching product instances:\",\n\t\t\terror,\n\t\t);\n\t\tthrow error;\n\t}\n}\n","/**\n * GraphQL Client for @htlkg/data\n *\n * Provides both client-side and server-side GraphQL capabilities using AWS Amplify Data.\n * The server-side functions use the Amplify Astro adapter for proper SSR support.\n *\n * For server-side usage, use `Astro.locals.amplifyClient` (zero-config, injected by middleware).\n */\n\nimport { generateClient as generateDataClient } from \"aws-amplify/data\";\nimport { Amplify } from \"aws-amplify\";\nimport type { ResourcesConfig } from \"aws-amplify\";\nimport { generateServerClientUsingCookies } from \"./server\";\n\n// Re-export server-side client generation (used internally by middleware)\nexport { generateServerClientUsingCookies } from \"./server\";\n\n// Re-export proxy functions for authenticated client-side operations\nexport {\n\tmutate,\n\tquery,\n\thasErrors,\n\tgetErrorMessage,\n\ttype Operation,\n\ttype GraphQLResponse,\n\ttype ProxyOptions,\n} from \"./proxy\";\n\n/**\n * Type for the server-side Amplify client (for use in type declarations)\n * This represents the client returned by generateServerClientUsingCookies\n */\nexport type AmplifyServerClient<TSchema extends Record<string, unknown> = Record<string, unknown>> =\n\tReturnType<typeof generateServerClientUsingCookies<TSchema>>;\n\n// Singleton client instance for client-side fetching\nlet sharedClientInstance: any = null;\n\n/**\n * Get or create the shared GraphQL client instance (singleton pattern)\n * Use this for client-side fetching to avoid creating multiple client instances.\n *\n * @example\n * ```typescript\n * const client = getSharedClient<Schema>();\n * const { data } = await client.models.Account.list();\n * ```\n */\nexport function getSharedClient<\n\tTSchema extends Record<string, unknown> = Record<string, unknown>,\n>(): ReturnType<typeof generateDataClient<TSchema>> {\n\tif (!sharedClientInstance) {\n\t\tsharedClientInstance = generateDataClient<TSchema>();\n\t}\n\treturn sharedClientInstance;\n}\n\n/**\n * Reset the shared client instance (useful for testing or auth state changes)\n */\nexport function resetSharedClient(): void {\n\tsharedClientInstance = null;\n}\n\n/**\n * Generate a client-side GraphQL client for use in Vue components and browser contexts\n * This is SSR-safe and should be called within a component's setup function or after hydration\n *\n * @example\n * ```typescript\n * import type { Schema } from '@backend/data/resource';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const { data: brands } = await client.models.Brand.list();\n * ```\n */\nexport function generateClient<\n\tTSchema extends Record<string, unknown> = Record<string, unknown>,\n>(): ReturnType<typeof generateDataClient<TSchema>> {\n\treturn generateDataClient<TSchema>();\n}\n\n/**\n * Configuration for Amplify (matches amplify_outputs.json format)\n */\nexport type AstroAmplifyConfig = ResourcesConfig;\n\n/**\n * Authentication mode for server-side GraphQL client\n */\nexport type ServerAuthMode = 'userPool' | 'apiKey';\n\n/**\n * Options for generating a server-side GraphQL client\n */\nexport interface GenerateServerClientOptions {\n\t/** Authentication mode - 'userPool' (default) uses JWT from cookies, 'apiKey' uses API key */\n\tauthMode?: ServerAuthMode;\n}\n\n/**\n * Generate a server-side GraphQL client for use within runWithAmplifyServerContext\n * \n * This function creates a GraphQL client that can be used for server-side data fetching in Astro.\n * It MUST be called within runWithAmplifyServerContext to access JWT tokens from cookies.\n * \n * The client supports two authentication modes:\n * - 'userPool' (default): Uses JWT tokens from cookies (requires runWithAmplifyServerContext)\n * - 'apiKey': Uses API key for public/unauthenticated requests\n *\n * **Important**: \n * - Amplify.configure() must be called once at app startup (e.g., in amplify-server.ts)\n * - This function must be called INSIDE the operation function of runWithAmplifyServerContext\n * - The context automatically provides the token provider that reads JWT tokens from cookies\n *\n * @example\n * ```typescript\n * // In your Astro page\n * import type { Schema } from '../amplify/data/resource';\n * import { generateServerClient } from '@htlkg/data/client';\n * import { createRunWithAmplifyServerContext } from '@htlkg/core/amplify-astro-adapter';\n * import outputs from '../amplify_outputs.json';\n *\n * const runWithAmplifyServerContext = createRunWithAmplifyServerContext({ config: outputs });\n *\n * // Fetch data with authentication\n * const result = await runWithAmplifyServerContext({\n * astroServerContext: {\n * cookies: Astro.cookies,\n * request: Astro.request\n * },\n * operation: async (contextSpec) => {\n * // Generate client INSIDE the operation\n * const client = generateServerClient<Schema>({ authMode: 'userPool' });\n * return await client.models.User.list();\n * }\n * });\n * \n * const users = result.data || [];\n * ```\n * \n * @example Using API key for public data\n * ```typescript\n * const result = await runWithAmplifyServerContext({\n * astroServerContext: {\n * cookies: Astro.cookies,\n * request: Astro.request\n * },\n * operation: async (contextSpec) => {\n * const client = generateServerClient<Schema>({ authMode: 'apiKey' });\n * return await client.models.Brand.list();\n * }\n * });\n * ```\n */\nexport function generateServerClient<\n\tTSchema extends Record<string, unknown> = Record<string, unknown>,\n>(_options?: GenerateServerClientOptions): ReturnType<typeof generateDataClient<TSchema>> {\n\t// Generate the client without authMode parameter\n\t// When called within runWithAmplifyServerContext, it will automatically use the token provider\n\t// from the context (which reads JWT tokens from cookies)\n\t// The authMode should be specified per-operation, not at client creation\n\tconst client = generateDataClient<TSchema>();\n\n\treturn client;\n}\n\n/**\n * Context required for getting a server client in API routes\n */\nexport interface ServerClientContext {\n\tlocals: { amplifyClient?: any; user?: any };\n\tcookies: any;\n\trequest: Request;\n}\n\n/**\n * Get the server client from Astro context\n *\n * Uses locals.amplifyClient if available (set by middleware),\n * otherwise creates a new client using Amplify's global config.\n * No config parameter needed - uses the config set by the middleware.\n *\n * @example\n * ```typescript\n * import { getServerClient } from '@htlkg/data/client';\n *\n * export const POST: APIRoute = async (context) => {\n * const client = getServerClient(context);\n * if (!client) return new Response('Not authenticated', { status: 401 });\n *\n * const result = await client.models.User.list();\n * };\n * ```\n */\nexport function getServerClient<TSchema extends Record<string, unknown> = Record<string, unknown>>(\n\tcontext: ServerClientContext,\n): ReturnType<typeof generateServerClientUsingCookies<TSchema>> | null {\n\t// Try to use client from middleware first\n\tif (context.locals.amplifyClient) {\n\t\treturn context.locals.amplifyClient as ReturnType<typeof generateServerClientUsingCookies<TSchema>>;\n\t}\n\n\t// If no client from middleware and user is authenticated, create one using global Amplify config\n\tif (context.locals.user) {\n\t\ttry {\n\t\t\t// Get config from Amplify (set by middleware)\n\t\t\tconst amplifyConfig = Amplify.getConfig();\n\t\t\tif (amplifyConfig) {\n\t\t\t\treturn generateServerClientUsingCookies<TSchema>({\n\t\t\t\t\tconfig: amplifyConfig,\n\t\t\t\t\tcookies: context.cookies,\n\t\t\t\t\trequest: context.request,\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tconsole.error('[getServerClient] Failed to get Amplify config:', e);\n\t\t}\n\t}\n\n\t// No authentication available\n\treturn null;\n}\n","/**\n * Server-side data client for Astro\n *\n * Provides a client generator similar to Next.js's generateServerClientUsingCookies\n * using generateClientWithAmplifyInstance for proper server context integration.\n */\n\nimport type { AstroGlobal } from \"astro\";\nimport type { ResourcesConfig } from \"aws-amplify\";\nimport {\n\tCommonPublicClientOptions,\n\tDefaultCommonClientOptions,\n\tV6ClientSSRCookies,\n\tgenerateClientWithAmplifyInstance,\n} from \"aws-amplify/api/internals\";\nimport { getAmplifyServerContext } from \"aws-amplify/adapter-core/internals\";\nimport { createRunWithAmplifyServerContext, createLogger } from \"@htlkg/core/amplify-astro-adapter\";\n\nconst log = createLogger('server-client');\n\ninterface AstroCookiesClientParams {\n\tcookies: AstroGlobal[\"cookies\"];\n\trequest: AstroGlobal[\"request\"];\n\tconfig: ResourcesConfig;\n}\n\n/**\n * Generates a server-side data client for Astro (matches Next.js implementation)\n *\n * This function creates a client that automatically wraps all operations in the Amplify server context,\n * ensuring that authentication tokens from cookies are properly used.\n *\n * @example\n * ```typescript\n * import type { Schema } from '../amplify/data/resource';\n * import { generateServerClientUsingCookies } from '@htlkg/data/client';\n * import { parseAmplifyConfig } from 'aws-amplify/utils';\n * import outputs from '../amplify_outputs.json';\n *\n * const amplifyConfig = parseAmplifyConfig(outputs);\n *\n * const client = generateServerClientUsingCookies<Schema>({\n * config: amplifyConfig,\n * cookies: Astro.cookies,\n * request: Astro.request,\n * });\n *\n * // Use the client directly - operations are automatically wrapped\n * const result = await client.models.User.list({\n * selectionSet: ['id', 'email'],\n * limit: 100,\n * });\n * ```\n */\nexport function generateServerClientUsingCookies<\n\tT extends Record<any, any> = never,\n\tOptions extends CommonPublicClientOptions &\n\t\tAstroCookiesClientParams = DefaultCommonClientOptions &\n\t\tAstroCookiesClientParams,\n>(options: Options): V6ClientSSRCookies<T, Options> {\n\tconst runWithAmplifyServerContext = createRunWithAmplifyServerContext({\n\t\tconfig: options.config,\n\t});\n\n\tconst resourcesConfig = options.config;\n\n\t// This function reference gets passed down to InternalGraphQLAPI.ts.graphql\n\t// where this._graphql is passed in as the `fn` argument\n\t// causing it to always get invoked inside `runWithAmplifyServerContext`\n\tconst getAmplify = (fn: (amplify: any) => Promise<any>) => {\n\t\treturn runWithAmplifyServerContext({\n\t\t\tastroServerContext: {\n\t\t\t\tcookies: options.cookies,\n\t\t\t\trequest: options.request,\n\t\t\t},\n\t\t\toperation: async (contextSpec: any) => {\n\t\t\t\tconst amplifyInstance = getAmplifyServerContext(contextSpec).amplify;\n\t\t\t\t\n\t\t\t\t// Debug logging (only when DEBUG=true)\n\t\t\t\ttry {\n\t\t\t\t\tconst config = amplifyInstance.getConfig();\n\t\t\t\t\tlog.debug('Amplify config from instance:', {\n\t\t\t\t\t\thasAPI: !!config.API,\n\t\t\t\t\t\thasGraphQL: !!config.API?.GraphQL,\n\t\t\t\t\t\tendpoint: config.API?.GraphQL?.endpoint,\n\t\t\t\t\t\tdefaultAuthMode: config.API?.GraphQL?.defaultAuthMode,\n\t\t\t\t\t\tregion: config.API?.GraphQL?.region,\n\t\t\t\t\t});\n\t\t\t\t\t\n\t\t\t\t\tconst session = await amplifyInstance.Auth.fetchAuthSession();\n\t\t\t\t\tlog.debug('Auth session:', {\n\t\t\t\t\t\thasTokens: !!session.tokens,\n\t\t\t\t\t\thasAccessToken: !!session.tokens?.accessToken,\n\t\t\t\t\t\thasIdToken: !!session.tokens?.idToken,\n\t\t\t\t\t\thasCredentials: !!session.credentials,\n\t\t\t\t\t});\n\t\t\t\t} catch (e: any) {\n\t\t\t\t\tlog.debug('Error fetching session:', e.message);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\treturn fn(amplifyInstance);\n\t\t\t},\n\t\t});\n\t};\n\n\tconst {\n\t\tcookies: _cookies,\n\t\trequest: _request,\n\t\tconfig: _config,\n\t\t...params\n\t} = options;\n\n\treturn generateClientWithAmplifyInstance<T, V6ClientSSRCookies<T, Options>>({\n\t\tamplify: getAmplify,\n\t\tconfig: resourcesConfig,\n\t\t...params,\n\t} as any);\n}\n","/**\n * Server-Side Query Helpers\n *\n * Convenience functions for executing server-side queries in Astro pages.\n * These helpers simplify the common pattern of using runWithAmplifyServerContext.\n */\n\nimport type { AstroGlobal } from \"astro\";\nimport { generateServerClient } from \"../client\";\n\n/**\n * Type for the runWithAmplifyServerContext function\n */\ntype RunWithAmplifyServerContext = (options: {\n\tastroServerContext: {\n\t\tcookies: AstroGlobal[\"cookies\"];\n\t\trequest: AstroGlobal[\"request\"];\n\t};\n\toperation: (contextSpec: unknown) => Promise<unknown>;\n}) => Promise<unknown>;\n\n/**\n * Helper to execute server-side queries in Astro pages\n *\n * This function wraps the common pattern of using runWithAmplifyServerContext\n * with generateServerClient, making it easier to fetch data server-side.\n *\n * **Note**: This requires `createRunWithAmplifyServerContext` from `@htlkg/core/amplify-astro-adapter`.\n * If you need more control, use the full pattern directly.\n *\n * @example\n * ```typescript\n * import type { Schema } from '../amplify/data/resource';\n * import { executeServerQuery } from '@htlkg/data/queries/server-helpers';\n * import { createRunWithAmplifyServerContext } from '@htlkg/core/amplify-astro-adapter';\n * import outputs from '../amplify_outputs.json';\n *\n * const runWithAmplifyServerContext = createRunWithAmplifyServerContext({ config: outputs });\n *\n * const users = await executeServerQuery<Schema>(\n * Astro,\n * runWithAmplifyServerContext,\n * async (client) => {\n * const result = await client.models.User.list();\n * return result.data || [];\n * }\n * );\n * ```\n */\nexport async function executeServerQuery<\n\tTSchema extends Record<string, unknown>,\n\tTResult,\n>(\n\tastro: AstroGlobal,\n\trunWithAmplifyServerContext: RunWithAmplifyServerContext,\n\toperation: (client: ReturnType<typeof generateServerClient<TSchema>>) => Promise<TResult>,\n): Promise<TResult> {\n\tconst result = await runWithAmplifyServerContext({\n\t\tastroServerContext: {\n\t\t\tcookies: astro.cookies,\n\t\t\trequest: astro.request,\n\t\t},\n\t\toperation: async (contextSpec: unknown) => {\n\t\t\tconst client = generateServerClient<TSchema>();\n\t\t\treturn await operation(client);\n\t\t},\n\t});\n\treturn result as TResult;\n}\n\n/**\n * Helper to execute server-side queries with API key authentication (public data)\n *\n * Use this for fetching public data that doesn't require user authentication.\n *\n * @example\n * ```typescript\n * import type { Schema } from '../amplify/data/resource';\n * import { executePublicQuery } from '@htlkg/data/queries/server-helpers';\n * import { createRunWithAmplifyServerContext } from '@htlkg/core/amplify-astro-adapter';\n * import outputs from '../amplify_outputs.json';\n *\n * const runWithAmplifyServerContext = createRunWithAmplifyServerContext({ config: outputs });\n *\n * const brands = await executePublicQuery<Schema>(\n * Astro,\n * runWithAmplifyServerContext,\n * async (client) => {\n * const result = await client.models.Brand.list();\n * return result.data || [];\n * }\n * );\n * ```\n */\nexport async function executePublicQuery<\n\tTSchema extends Record<string, unknown>,\n\tTResult,\n>(\n\tastro: AstroGlobal,\n\trunWithAmplifyServerContext: RunWithAmplifyServerContext,\n\toperation: (client: ReturnType<typeof generateServerClient<TSchema>>) => Promise<TResult>,\n): Promise<TResult> {\n\tconst result = await runWithAmplifyServerContext({\n\t\tastroServerContext: {\n\t\t\tcookies: astro.cookies,\n\t\t\trequest: astro.request,\n\t\t},\n\t\toperation: async (_contextSpec: unknown) => {\n\t\t\tconst client = generateServerClient<TSchema>({ authMode: \"apiKey\" });\n\t\t\treturn await operation(client);\n\t\t},\n\t});\n\treturn result as TResult;\n}\n","/**\n * SystemSettings Query Functions\n *\n * Provides query functions for fetching system settings from the GraphQL API.\n */\n\nimport type { SystemSettings } from \"@htlkg/core/types\";\n\n/** Default retention days if no settings exist */\nexport const DEFAULT_SOFT_DELETE_RETENTION_DAYS = 30;\n\n/** The key used for global system settings */\nexport const SYSTEM_SETTINGS_KEY = \"GLOBAL\";\n\n/**\n * Get system settings\n *\n * @example\n * ```typescript\n * import { getSystemSettings } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const settings = await getSystemSettings(client);\n * ```\n */\nexport async function getSystemSettings<TClient = any>(\n\tclient: TClient,\n): Promise<SystemSettings | null> {\n\ttry {\n\t\tconst { data, errors } = await (client as any).models.SystemSettings.get({\n\t\t\tkey: SYSTEM_SETTINGS_KEY,\n\t\t});\n\n\t\tif (errors) {\n\t\t\tconsole.error(\"[getSystemSettings] GraphQL errors:\", errors);\n\t\t\treturn null;\n\t\t}\n\n\t\treturn data as SystemSettings;\n\t} catch (error) {\n\t\tconsole.error(\"[getSystemSettings] Error fetching system settings:\", error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * Get the soft delete retention days from system settings\n * Returns the default (30 days) if settings don't exist\n *\n * @example\n * ```typescript\n * import { getSoftDeleteRetentionDays } from '@htlkg/data/queries';\n * import { generateClient } from '@htlkg/data/client';\n *\n * const client = generateClient<Schema>();\n * const days = await getSoftDeleteRetentionDays(client);\n * ```\n */\nexport async function getSoftDeleteRetentionDays<TClient = any>(\n\tclient: TClient,\n): Promise<number> {\n\tconst settings = await getSystemSettings(client);\n\treturn settings?.softDeleteRetentionDays ?? DEFAULT_SOFT_DELETE_RETENTION_DAYS;\n}\n\n/**\n * Check if a soft-deleted item can still be restored based on retention period\n *\n * @param deletedAt - The ISO date string when the item was deleted\n * @param retentionDays - Number of days items can be restored\n * @returns Object with canRestore flag and daysRemaining/daysExpired\n */\nexport function checkRestoreEligibility(\n\tdeletedAt: string | undefined | null,\n\tretentionDays: number,\n): {\n\tcanRestore: boolean;\n\tdaysRemaining: number;\n\tdaysExpired: number;\n\texpiresAt: Date | null;\n} {\n\tif (!deletedAt) {\n\t\treturn {\n\t\t\tcanRestore: false,\n\t\t\tdaysRemaining: 0,\n\t\t\tdaysExpired: 0,\n\t\t\texpiresAt: null,\n\t\t};\n\t}\n\n\tconst deletedDate = new Date(deletedAt);\n\tconst expiresAt = new Date(deletedDate);\n\texpiresAt.setDate(expiresAt.getDate() + retentionDays);\n\n\tconst now = new Date();\n\tconst msRemaining = expiresAt.getTime() - now.getTime();\n\tconst daysRemaining = Math.ceil(msRemaining / (1000 * 60 * 60 * 24));\n\n\tif (daysRemaining <= 0) {\n\t\treturn {\n\t\t\tcanRestore: false,\n\t\t\tdaysRemaining: 0,\n\t\t\tdaysExpired: Math.abs(daysRemaining),\n\t\t\texpiresAt,\n\t\t};\n\t}\n\n\treturn {\n\t\tcanRestore: true,\n\t\tdaysRemaining,\n\t\tdaysExpired: 0,\n\t\texpiresAt,\n\t};\n}\n"],"mappings":";AAoBA,eAAsB,SACrB,QACA,IACwB;AACxB,MAAI;AACH,UAAM,EAAE,MAAM,OAAO,IAAI,MAAO,OAAe,OAAO,MAAM,IAAI,EAAE,GAAG,CAAC;AAEtE,QAAI,QAAQ;AACX,cAAQ,MAAM,8BAA8B,MAAM;AAClD,aAAO;AAAA,IACR;AAEA,WAAO;AAAA,EACR,SAAS,OAAO;AACf,YAAQ,MAAM,oCAAoC,KAAK;AACvD,UAAM;AAAA,EACP;AACD;AAgBA,eAAsB,WACrB,QACA,SAKkD;AAClD,MAAI;AACH,UAAM,EAAE,MAAM,QAAQ,UAAU,IAAI,MAAO,OAAe,OAAO,MAAM;AAAA,MACtE;AAAA,IACD;AAEA,QAAI,QAAQ;AACX,cAAQ,MAAM,gCAAgC,MAAM;AACpD,aAAO,EAAE,OAAO,CAAC,GAAG,WAAW,OAAU;AAAA,IAC1C;AAEA,WAAO;AAAA,MACN,OAAQ,QAAQ,CAAC;AAAA,MACjB;AAAA,IACD;AAAA,EACD,SAAS,OAAO;AACf,YAAQ,MAAM,uCAAuC,KAAK;AAC1D,UAAM;AAAA,EACP;AACD;AAcA,eAAsB,qBACrB,QACA,IACwB;AACxB,MAAI;AACH,UAAM,EAAE,MAAM,OAAO,IAAI,MAAO,OAAe,OAAO,MAAM;AAAA,MAC3D,EAAE,GAAG;AAAA,MACL;AAAA,QACC,cAAc;AAAA,UACb;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,QACD;AAAA,MACD;AAAA,IACD;AAEA,QAA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,WAAO;AAAA,MACN,YAAY;AAAA,MACZ,eAAe;AAAA,MACf,aAAa;AAAA,MACb,WAAW;AAAA,IACZ;AAAA,EACD;AAEA,QAAM,cAAc,IAAI,KAAK,SAAS;AACtC,QAAM,YAAY,IAAI,KAAK,WAAW;AACtC,YAAU,QAAQ,UAAU,QAAQ,IAAI,aAAa;AAErD,QAAM,MAAM,oBAAI,KAAK;AACrB,QAAM,cAAc,UAAU,QAAQ,IAAI,IAAI,QAAQ;AACtD,QAAM,gBAAgB,KAAK,KAAK,eAAe,MAAO,KAAK,KAAK,GAAG;AAEnE,MAAI,iBAAiB,GAAG;AACvB,WAAO;AAAA,MACN,YAAY;AAAA,MACZ,eAAe;AAAA,MACf,aAAa,KAAK,IAAI,aAAa;AAAA,MACnC;AAAA,IACD;AAAA,EACD;AAEA,SAAO;AAAA,IACN,YAAY;AAAA,IACZ;AAAA,IACA,aAAa;AAAA,IACb;AAAA,EACD;AACD;","names":[]}
@@ -0,0 +1,47 @@
1
+ import { AstroGlobal } from 'astro';
2
+ import { ResourcesConfig } from 'aws-amplify';
3
+ import { CommonPublicClientOptions, DefaultCommonClientOptions, V6ClientSSRCookies } from 'aws-amplify/api/internals';
4
+
5
+ /**
6
+ * Server-side data client for Astro
7
+ *
8
+ * Provides a client generator similar to Next.js's generateServerClientUsingCookies
9
+ * using generateClientWithAmplifyInstance for proper server context integration.
10
+ */
11
+
12
+ interface AstroCookiesClientParams {
13
+ cookies: AstroGlobal["cookies"];
14
+ request: AstroGlobal["request"];
15
+ config: ResourcesConfig;
16
+ }
17
+ /**
18
+ * Generates a server-side data client for Astro (matches Next.js implementation)
19
+ *
20
+ * This function creates a client that automatically wraps all operations in the Amplify server context,
21
+ * ensuring that authentication tokens from cookies are properly used.
22
+ *
23
+ * @example
24
+ * ```typescript
25
+ * import type { Schema } from '../amplify/data/resource';
26
+ * import { generateServerClientUsingCookies } from '@htlkg/data/client';
27
+ * import { parseAmplifyConfig } from 'aws-amplify/utils';
28
+ * import outputs from '../amplify_outputs.json';
29
+ *
30
+ * const amplifyConfig = parseAmplifyConfig(outputs);
31
+ *
32
+ * const client = generateServerClientUsingCookies<Schema>({
33
+ * config: amplifyConfig,
34
+ * cookies: Astro.cookies,
35
+ * request: Astro.request,
36
+ * });
37
+ *
38
+ * // Use the client directly - operations are automatically wrapped
39
+ * const result = await client.models.User.list({
40
+ * selectionSet: ['id', 'email'],
41
+ * limit: 100,
42
+ * });
43
+ * ```
44
+ */
45
+ declare function generateServerClientUsingCookies<T extends Record<any, any> = never, Options extends CommonPublicClientOptions & AstroCookiesClientParams = DefaultCommonClientOptions & AstroCookiesClientParams>(options: Options): V6ClientSSRCookies<T, Options>;
46
+
47
+ export { generateServerClientUsingCookies };
@@ -0,0 +1,59 @@
1
+ // src/client/server.ts
2
+ import {
3
+ generateClientWithAmplifyInstance
4
+ } from "aws-amplify/api/internals";
5
+ import { getAmplifyServerContext } from "aws-amplify/adapter-core/internals";
6
+ import { createRunWithAmplifyServerContext, createLogger } from "@htlkg/core/amplify-astro-adapter";
7
+ var log = createLogger("server-client");
8
+ function generateServerClientUsingCookies(options) {
9
+ const runWithAmplifyServerContext = createRunWithAmplifyServerContext({
10
+ config: options.config
11
+ });
12
+ const resourcesConfig = options.config;
13
+ const getAmplify = (fn) => {
14
+ return runWithAmplifyServerContext({
15
+ astroServerContext: {
16
+ cookies: options.cookies,
17
+ request: options.request
18
+ },
19
+ operation: async (contextSpec) => {
20
+ const amplifyInstance = getAmplifyServerContext(contextSpec).amplify;
21
+ try {
22
+ const config = amplifyInstance.getConfig();
23
+ log.debug("Amplify config from instance:", {
24
+ hasAPI: !!config.API,
25
+ hasGraphQL: !!config.API?.GraphQL,
26
+ endpoint: config.API?.GraphQL?.endpoint,
27
+ defaultAuthMode: config.API?.GraphQL?.defaultAuthMode,
28
+ region: config.API?.GraphQL?.region
29
+ });
30
+ const session = await amplifyInstance.Auth.fetchAuthSession();
31
+ log.debug("Auth session:", {
32
+ hasTokens: !!session.tokens,
33
+ hasAccessToken: !!session.tokens?.accessToken,
34
+ hasIdToken: !!session.tokens?.idToken,
35
+ hasCredentials: !!session.credentials
36
+ });
37
+ } catch (e) {
38
+ log.debug("Error fetching session:", e.message);
39
+ }
40
+ return fn(amplifyInstance);
41
+ }
42
+ });
43
+ };
44
+ const {
45
+ cookies: _cookies,
46
+ request: _request,
47
+ config: _config,
48
+ ...params
49
+ } = options;
50
+ return generateClientWithAmplifyInstance({
51
+ amplify: getAmplify,
52
+ config: resourcesConfig,
53
+ ...params
54
+ });
55
+ }
56
+ export {
57
+ generateServerClientUsingCookies
58
+ };
59
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/client/server.ts"],"sourcesContent":["/**\n * Server-side data client for Astro\n *\n * Provides a client generator similar to Next.js's generateServerClientUsingCookies\n * using generateClientWithAmplifyInstance for proper server context integration.\n */\n\nimport type { AstroGlobal } from \"astro\";\nimport type { ResourcesConfig } from \"aws-amplify\";\nimport {\n\tCommonPublicClientOptions,\n\tDefaultCommonClientOptions,\n\tV6ClientSSRCookies,\n\tgenerateClientWithAmplifyInstance,\n} from \"aws-amplify/api/internals\";\nimport { getAmplifyServerContext } from \"aws-amplify/adapter-core/internals\";\nimport { createRunWithAmplifyServerContext, createLogger } from \"@htlkg/core/amplify-astro-adapter\";\n\nconst log = createLogger('server-client');\n\ninterface AstroCookiesClientParams {\n\tcookies: AstroGlobal[\"cookies\"];\n\trequest: AstroGlobal[\"request\"];\n\tconfig: ResourcesConfig;\n}\n\n/**\n * Generates a server-side data client for Astro (matches Next.js implementation)\n *\n * This function creates a client that automatically wraps all operations in the Amplify server context,\n * ensuring that authentication tokens from cookies are properly used.\n *\n * @example\n * ```typescript\n * import type { Schema } from '../amplify/data/resource';\n * import { generateServerClientUsingCookies } from '@htlkg/data/client';\n * import { parseAmplifyConfig } from 'aws-amplify/utils';\n * import outputs from '../amplify_outputs.json';\n *\n * const amplifyConfig = parseAmplifyConfig(outputs);\n *\n * const client = generateServerClientUsingCookies<Schema>({\n * config: amplifyConfig,\n * cookies: Astro.cookies,\n * request: Astro.request,\n * });\n *\n * // Use the client directly - operations are automatically wrapped\n * const result = await client.models.User.list({\n * selectionSet: ['id', 'email'],\n * limit: 100,\n * });\n * ```\n */\nexport function generateServerClientUsingCookies<\n\tT extends Record<any, any> = never,\n\tOptions extends CommonPublicClientOptions &\n\t\tAstroCookiesClientParams = DefaultCommonClientOptions &\n\t\tAstroCookiesClientParams,\n>(options: Options): V6ClientSSRCookies<T, Options> {\n\tconst runWithAmplifyServerContext = createRunWithAmplifyServerContext({\n\t\tconfig: options.config,\n\t});\n\n\tconst resourcesConfig = options.config;\n\n\t// This function reference gets passed down to InternalGraphQLAPI.ts.graphql\n\t// where this._graphql is passed in as the `fn` argument\n\t// causing it to always get invoked inside `runWithAmplifyServerContext`\n\tconst getAmplify = (fn: (amplify: any) => Promise<any>) => {\n\t\treturn runWithAmplifyServerContext({\n\t\t\tastroServerContext: {\n\t\t\t\tcookies: options.cookies,\n\t\t\t\trequest: options.request,\n\t\t\t},\n\t\t\toperation: async (contextSpec: any) => {\n\t\t\t\tconst amplifyInstance = getAmplifyServerContext(contextSpec).amplify;\n\t\t\t\t\n\t\t\t\t// Debug logging (only when DEBUG=true)\n\t\t\t\ttry {\n\t\t\t\t\tconst config = amplifyInstance.getConfig();\n\t\t\t\t\tlog.debug('Amplify config from instance:', {\n\t\t\t\t\t\thasAPI: !!config.API,\n\t\t\t\t\t\thasGraphQL: !!config.API?.GraphQL,\n\t\t\t\t\t\tendpoint: config.API?.GraphQL?.endpoint,\n\t\t\t\t\t\tdefaultAuthMode: config.API?.GraphQL?.defaultAuthMode,\n\t\t\t\t\t\tregion: config.API?.GraphQL?.region,\n\t\t\t\t\t});\n\t\t\t\t\t\n\t\t\t\t\tconst session = await amplifyInstance.Auth.fetchAuthSession();\n\t\t\t\t\tlog.debug('Auth session:', {\n\t\t\t\t\t\thasTokens: !!session.tokens,\n\t\t\t\t\t\thasAccessToken: !!session.tokens?.accessToken,\n\t\t\t\t\t\thasIdToken: !!session.tokens?.idToken,\n\t\t\t\t\t\thasCredentials: !!session.credentials,\n\t\t\t\t\t});\n\t\t\t\t} catch (e: any) {\n\t\t\t\t\tlog.debug('Error fetching session:', e.message);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\treturn fn(amplifyInstance);\n\t\t\t},\n\t\t});\n\t};\n\n\tconst {\n\t\tcookies: _cookies,\n\t\trequest: _request,\n\t\tconfig: _config,\n\t\t...params\n\t} = options;\n\n\treturn generateClientWithAmplifyInstance<T, V6ClientSSRCookies<T, Options>>({\n\t\tamplify: getAmplify,\n\t\tconfig: resourcesConfig,\n\t\t...params,\n\t} as any);\n}\n"],"mappings":";AASA;AAAA,EAIC;AAAA,OACM;AACP,SAAS,+BAA+B;AACxC,SAAS,mCAAmC,oBAAoB;AAEhE,IAAM,MAAM,aAAa,eAAe;AAoCjC,SAAS,iCAKd,SAAkD;AACnD,QAAM,8BAA8B,kCAAkC;AAAA,IACrE,QAAQ,QAAQ;AAAA,EACjB,CAAC;AAED,QAAM,kBAAkB,QAAQ;AAKhC,QAAM,aAAa,CAAC,OAAuC;AAC1D,WAAO,4BAA4B;AAAA,MAClC,oBAAoB;AAAA,QACnB,SAAS,QAAQ;AAAA,QACjB,SAAS,QAAQ;AAAA,MAClB;AAAA,MACA,WAAW,OAAO,gBAAqB;AACtC,cAAM,kBAAkB,wBAAwB,WAAW,EAAE;AAG7D,YAAI;AACH,gBAAM,SAAS,gBAAgB,UAAU;AACzC,cAAI,MAAM,iCAAiC;AAAA,YAC1C,QAAQ,CAAC,CAAC,OAAO;AAAA,YACjB,YAAY,CAAC,CAAC,OAAO,KAAK;AAAA,YAC1B,UAAU,OAAO,KAAK,SAAS;AAAA,YAC/B,iBAAiB,OAAO,KAAK,SAAS;AAAA,YACtC,QAAQ,OAAO,KAAK,SAAS;AAAA,UAC9B,CAAC;AAED,gBAAM,UAAU,MAAM,gBAAgB,KAAK,iBAAiB;AAC5D,cAAI,MAAM,iBAAiB;AAAA,YAC1B,WAAW,CAAC,CAAC,QAAQ;AAAA,YACrB,gBAAgB,CAAC,CAAC,QAAQ,QAAQ;AAAA,YAClC,YAAY,CAAC,CAAC,QAAQ,QAAQ;AAAA,YAC9B,gBAAgB,CAAC,CAAC,QAAQ;AAAA,UAC3B,CAAC;AAAA,QACF,SAAS,GAAQ;AAChB,cAAI,MAAM,2BAA2B,EAAE,OAAO;AAAA,QAC/C;AAEA,eAAO,GAAG,eAAe;AAAA,MAC1B;AAAA,IACD,CAAC;AAAA,EACF;AAEA,QAAM;AAAA,IACL,SAAS;AAAA,IACT,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,GAAG;AAAA,EACJ,IAAI;AAEJ,SAAO,kCAAqE;AAAA,IAC3E,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,GAAG;AAAA,EACJ,CAAQ;AACT;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@htlkg/data",
3
- "version": "0.0.15",
3
+ "version": "0.0.16",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -11,6 +11,10 @@
11
11
  "import": "./dist/client/index.js",
12
12
  "types": "./dist/client/index.d.ts"
13
13
  },
14
+ "./server": {
15
+ "import": "./dist/server/index.js",
16
+ "types": "./dist/server/index.d.ts"
17
+ },
14
18
  "./queries": {
15
19
  "import": "./dist/queries/index.js",
16
20
  "types": "./dist/queries/index.d.ts"
@@ -39,7 +43,7 @@
39
43
  "dependencies": {
40
44
  "@aws-amplify/api": "^6.0.0",
41
45
  "zod": "^3.22.0",
42
- "@htlkg/core": "0.0.14"
46
+ "@htlkg/core": "0.0.13"
43
47
  },
44
48
  "peerDependencies": {
45
49
  "vue": "^3.5.0"
@@ -3,14 +3,36 @@
3
3
  *
4
4
  * Provides both client-side and server-side GraphQL capabilities using AWS Amplify Data.
5
5
  * The server-side functions use the Amplify Astro adapter for proper SSR support.
6
+ *
7
+ * For server-side usage, use `Astro.locals.amplifyClient` (zero-config, injected by middleware).
6
8
  */
7
9
 
8
10
  import { generateClient as generateDataClient } from "aws-amplify/data";
11
+ import { Amplify } from "aws-amplify";
9
12
  import type { ResourcesConfig } from "aws-amplify";
13
+ import { generateServerClientUsingCookies } from "./server";
10
14
 
11
- // Re-export server-side client generation
15
+ // Re-export server-side client generation (used internally by middleware)
12
16
  export { generateServerClientUsingCookies } from "./server";
13
17
 
18
+ // Re-export proxy functions for authenticated client-side operations
19
+ export {
20
+ mutate,
21
+ query,
22
+ hasErrors,
23
+ getErrorMessage,
24
+ type Operation,
25
+ type GraphQLResponse,
26
+ type ProxyOptions,
27
+ } from "./proxy";
28
+
29
+ /**
30
+ * Type for the server-side Amplify client (for use in type declarations)
31
+ * This represents the client returned by generateServerClientUsingCookies
32
+ */
33
+ export type AmplifyServerClient<TSchema extends Record<string, unknown> = Record<string, unknown>> =
34
+ ReturnType<typeof generateServerClientUsingCookies<TSchema>>;
35
+
14
36
  // Singleton client instance for client-side fetching
15
37
  let sharedClientInstance: any = null;
16
38
 
@@ -134,12 +156,69 @@ export interface GenerateServerClientOptions {
134
156
  */
135
157
  export function generateServerClient<
136
158
  TSchema extends Record<string, unknown> = Record<string, unknown>,
137
- >(options?: GenerateServerClientOptions): ReturnType<typeof generateDataClient<TSchema>> {
159
+ >(_options?: GenerateServerClientOptions): ReturnType<typeof generateDataClient<TSchema>> {
138
160
  // Generate the client without authMode parameter
139
161
  // When called within runWithAmplifyServerContext, it will automatically use the token provider
140
162
  // from the context (which reads JWT tokens from cookies)
141
163
  // The authMode should be specified per-operation, not at client creation
142
164
  const client = generateDataClient<TSchema>();
143
-
165
+
144
166
  return client;
145
167
  }
168
+
169
+ /**
170
+ * Context required for getting a server client in API routes
171
+ */
172
+ export interface ServerClientContext {
173
+ locals: { amplifyClient?: any; user?: any };
174
+ cookies: any;
175
+ request: Request;
176
+ }
177
+
178
+ /**
179
+ * Get the server client from Astro context
180
+ *
181
+ * Uses locals.amplifyClient if available (set by middleware),
182
+ * otherwise creates a new client using Amplify's global config.
183
+ * No config parameter needed - uses the config set by the middleware.
184
+ *
185
+ * @example
186
+ * ```typescript
187
+ * import { getServerClient } from '@htlkg/data/client';
188
+ *
189
+ * export const POST: APIRoute = async (context) => {
190
+ * const client = getServerClient(context);
191
+ * if (!client) return new Response('Not authenticated', { status: 401 });
192
+ *
193
+ * const result = await client.models.User.list();
194
+ * };
195
+ * ```
196
+ */
197
+ export function getServerClient<TSchema extends Record<string, unknown> = Record<string, unknown>>(
198
+ context: ServerClientContext,
199
+ ): ReturnType<typeof generateServerClientUsingCookies<TSchema>> | null {
200
+ // Try to use client from middleware first
201
+ if (context.locals.amplifyClient) {
202
+ return context.locals.amplifyClient as ReturnType<typeof generateServerClientUsingCookies<TSchema>>;
203
+ }
204
+
205
+ // If no client from middleware and user is authenticated, create one using global Amplify config
206
+ if (context.locals.user) {
207
+ try {
208
+ // Get config from Amplify (set by middleware)
209
+ const amplifyConfig = Amplify.getConfig();
210
+ if (amplifyConfig) {
211
+ return generateServerClientUsingCookies<TSchema>({
212
+ config: amplifyConfig,
213
+ cookies: context.cookies,
214
+ request: context.request,
215
+ });
216
+ }
217
+ } catch (e) {
218
+ console.error('[getServerClient] Failed to get Amplify config:', e);
219
+ }
220
+ }
221
+
222
+ // No authentication available
223
+ return null;
224
+ }