@ehrenkind/shopify-lib 0.5.1 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/utils/logger.ts","../src/utils/shopifyClient.ts","../src/utils/apiVersion.ts","../src/utils/shopifyFetch.ts","../src/mutations/customers/deleteCustomerById.ts","../src/mutations/files/deleteFilesByIds.ts","../src/mutations/files/createFile.ts","../src/mutations/metaobjectDefinitions/createMetaobjectDefinition.ts","../src/mutations/fulfillments/createFulfillment.ts","../src/queries/fulfillments/getFulfillmentTrackingIds.queries.ts","../src/queries/fulfillments/getFulfillmentTrackingIds.ts","../src/mutations/fulfillments/updateFulfillmentTracking.ts","../src/mutations/orders/cancelOrderById.ts","../src/mutations/refunds/createRefund.ts","../src/mutations/productVariantsBulkUpdate/bulkUpdateProductVariants.ts","../src/mutations/metaobjects/upsertMetaobject.ts","../src/queries/orders/calculateRefund.queries.ts","../src/queries/orders/calculateRefund.ts","../src/queries/orders/getOrderById.ts","../src/utils/zod.ts","../src/queries/orders/getOrderById.queries.ts","../src/queries/orders/getOrderByName.ts","../src/queries/orders/getOrderByName.queries.ts","../src/queries/orders/getOrderCancellationInfo.queries.ts","../src/queries/orders/getOrderCancellationInfo.ts","../src/queries/productVariants/getLeanProductVariants.ts","../src/queries/productVariants/getProductVariantsBySkus.ts","../src/queries/productVariants/getAllProductVariants.ts","../src/queries/productVariants/getAllProductVariants.queries.ts","../src/queries/orders/getOrderPaymentDetails.queries.ts","../src/queries/orders/getOrderPaymentDetails.ts","../src/queries/fulfillments/getFulfillmentById.queries.ts","../src/queries/fulfillments/getFulfillmentById.ts","../src/queries/fulfillmentOrders/getFulfillmentOrdersByOrderId.queries.ts","../src/queries/fulfillmentOrders/getFulfillmentOrdersByOrderId.ts","../src/queries/customers/getCustomersByEmail.queries.ts","../src/queries/customers/getCustomersByEmail.ts","../src/queries/customerSegments/getCustomerSegmentMembers.queries.ts","../src/queries/customerSegments/getCustomerSegmentMembers.ts","../src/queries/orders/getOrdersByCustomerId.queries.ts","../src/queries/orders/getOrdersByCustomerId.ts","../src/utils/parseGid.ts","../src/queries/metaobjects/getMetaobjectByHandle.queries.ts","../src/queries/metaobjects/getMetaobjectByHandle.ts"],"sourcesContent":["export { deleteCustomerById } from './mutations/customers/deleteCustomerById.js'\nexport { deleteFilesByIds } from './mutations/files/deleteFilesByIds.js'\nexport { createFile } from './mutations/files/createFile.js'\nexport {\n createMetaobjectDefinition,\n type CreateMetaobjectDefinitionInput,\n type CreateMetaobjectDefinitionResult,\n type MetaobjectFieldDefinition,\n} from './mutations/metaobjectDefinitions/createMetaobjectDefinition.js'\nexport {\n createFulfillment,\n type CreateFulfillmentResult,\n type FulfillmentLineItem,\n} from './mutations/fulfillments/createFulfillment.js'\nexport {\n updateFulfillmentTracking,\n type UpdateFulfillmentTrackingResult,\n} from './mutations/fulfillments/updateFulfillmentTracking.js'\nexport { cancelOrderById } from './mutations/orders/cancelOrderById.js'\nexport {\n createRefund,\n type CreateRefundOptions,\n type CreateRefundResult,\n type CreateRefundLineItem,\n type CreateRefundTransaction,\n type RefundMoney,\n} from './mutations/refunds/createRefund.js'\nexport {\n bulkUpdateProductVariants,\n type BulkUpdateProductVariantsResult,\n type VariantUpdateInput,\n} from './mutations/productVariantsBulkUpdate/bulkUpdateProductVariants.js'\nexport {\n upsertMetaobject,\n type UpsertMetaobjectInput,\n type UpsertMetaobjectResult,\n} from './mutations/metaobjects/upsertMetaobject.js'\nexport {\n calculateRefund,\n type CalculateRefundOptions,\n type CalculateRefundLineItem,\n type SuggestedRefund,\n} from './queries/orders/calculateRefund.js'\nexport {\n ShopifyUserError,\n type ShopifyUserErrorDetail,\n} from './utils/shopifyFetch.js'\nexport {\n getOrderById,\n type FullOrder,\n type LeanOrder,\n} from './queries/orders/getOrderById.js'\nexport {\n getOrderByName,\n type FullOrderByName,\n type LeanOrderByName,\n} from './queries/orders/getOrderByName.js'\nexport {\n getOrderCancellationInfoByName,\n type OrderCancellationInfo,\n} from './queries/orders/getOrderCancellationInfo.js'\nexport {\n getLeanProductVariants,\n type LeanProductVariant,\n type LeanProductVariantsOptions,\n} from './queries/productVariants/getLeanProductVariants.js'\nexport {\n getProductVariantsBySkus,\n type ProductVariantBySku,\n type ProductVariantsBySkusOptions,\n} from './queries/productVariants/getProductVariantsBySkus.js'\nexport {\n getAllProductVariants,\n type ProductVariant,\n} from './queries/productVariants/getAllProductVariants.js'\nexport {\n getOrderPaymentDetailsById,\n type OrderPaymentDetails,\n} from './queries/orders/getOrderPaymentDetails.js'\nexport {\n getFulfillmentById,\n type Fulfillment,\n} from './queries/fulfillments/getFulfillmentById.js'\nexport {\n getFulfillmentOrdersByOrderId,\n type FulfillmentOrder,\n} from './queries/fulfillmentOrders/getFulfillmentOrdersByOrderId.js'\nexport {\n getFulfillmentTrackingIds,\n type FulfillmentTrackingIds,\n} from './queries/fulfillments/getFulfillmentTrackingIds.js'\nexport {\n getCustomersByEmail,\n type Customer,\n} from './queries/customers/getCustomersByEmail.js'\nexport {\n getCustomerSegmentMembers,\n type CustomerSegmentMember,\n type CustomerSegmentMembersResult,\n type SegmentAttributeStatistics,\n} from './queries/customerSegments/getCustomerSegmentMembers.js'\nexport {\n getOrdersByCustomerId,\n type OrderPreview,\n} from './queries/orders/getOrdersByCustomerId.js'\nexport { parseGid } from './utils/parseGid.js'\nexport {\n getMetaobjectByHandle,\n type Metaobject,\n} from './queries/metaobjects/getMetaobjectByHandle.js'\nexport type { MetaobjectHandleInput } from './generated-api-types/2025-04/admin.types.js'\n","const { env } = process\n\nexport const gql = String.raw\n\nconst logLevels = {\n silent: 0,\n error: 1,\n warn: 2,\n info: 3,\n debug: 4,\n} as const\n\ntype LogLevelName = keyof typeof logLevels\n\nfunction getLogLevel(\n nodeEnv: string | undefined,\n logLevelEnv: string | undefined,\n): LogLevelName {\n if (logLevelEnv && logLevelEnv in logLevels) {\n return logLevelEnv as LogLevelName\n }\n\n if (nodeEnv === 'test') {\n return 'silent'\n }\n\n if (nodeEnv === 'production') {\n return 'info'\n }\n return 'debug'\n}\n\nexport const activeLogLevelName = getLogLevel(env.NODE_ENV, env.LOG_LEVEL)\nconst activeLogLevelValue = logLevels[activeLogLevelName]\n\nexport const logger = {\n debug: (...args: unknown[]) => {\n if (logLevels.debug <= activeLogLevelValue) {\n // biome-ignore lint/suspicious/noConsole: <explanation>\n console.debug(...args)\n }\n },\n info: (...args: unknown[]) => {\n if (logLevels.info <= activeLogLevelValue) {\n // biome-ignore lint/suspicious/noConsole: <explanation>\n console.info(...args)\n }\n },\n warn: (...args: unknown[]) => {\n if (logLevels.warn <= activeLogLevelValue) {\n // biome-ignore lint/suspicious/noConsole: <explanation>\n console.warn(...args)\n }\n },\n error: (...args: unknown[]) => {\n if (logLevels.error <= activeLogLevelValue) {\n // biome-ignore lint/suspicious/noConsole: <explanation>\n console.error(...args)\n }\n },\n}\n","import {\n type GraphqlClient,\n LogSeverity,\n Session,\n shopifyApi,\n} from '@shopify/shopify-api'\nimport '@shopify/shopify-api/adapters/node'\nimport dotenv from 'dotenv'\nimport { z } from 'zod'\nimport { SHOPIFY_API_VERSION } from './apiVersion.js'\nimport { activeLogLevelName, logger } from './logger.js'\n\nexport { SHOPIFY_API_VERSION }\n\ndotenv.config()\n\nconst envSchema = z.object({\n SHOPIFY_API_KEY: z.string({\n required_error: 'SHOPIFY_API_KEY is required',\n }),\n SHOPIFY_API_SECRET: z.string({\n required_error: 'SHOPIFY_API_SECRET is required',\n }),\n SHOPIFY_API_HOSTNAME: z.string({\n required_error: 'SHOPIFY_API_HOSTNAME is required',\n }),\n SHOPIFY_ACCESS_TOKEN: z.string({\n required_error: 'SHOPIFY_ACCESS_TOKEN is required',\n }),\n NODE_ENV: z\n .enum(['development', 'production', 'test'])\n .default('development'),\n})\n\nconst mapLogLevelToShopifySeverity = (level: string): LogSeverity => {\n switch (level) {\n case 'silent':\n return LogSeverity.Error\n case 'debug':\n return LogSeverity.Debug\n case 'info':\n return LogSeverity.Info\n case 'warn':\n return LogSeverity.Warning\n case 'error':\n return LogSeverity.Error\n default:\n return LogSeverity.Info\n }\n}\n\nlet shopifyGraphqlClient: GraphqlClient\n\ntry {\n // biome-ignore lint/nursery/noProcessEnv: <explanation>\n const env = envSchema.parse(process.env)\n\n const shopify = shopifyApi({\n apiKey: env.SHOPIFY_API_KEY,\n apiSecretKey: env.SHOPIFY_API_SECRET,\n hostName: env.SHOPIFY_API_HOSTNAME,\n apiVersion: SHOPIFY_API_VERSION,\n isEmbeddedApp: false,\n logger: { level: mapLogLevelToShopifySeverity(activeLogLevelName) },\n future: {\n customerAddressDefaultFix: true,\n lineItemBilling: true,\n unstable_managedPricingSupport: false,\n },\n })\n\n const shopifySession = new Session({\n id: `custom-session-${env.SHOPIFY_API_HOSTNAME}`,\n shop: env.SHOPIFY_API_HOSTNAME,\n state: 'authenticated',\n isOnline: true,\n accessToken: env.SHOPIFY_ACCESS_TOKEN,\n })\n\n shopifyGraphqlClient = new shopify.clients.Graphql({\n session: shopifySession,\n })\n\n logger.info('Shopify API client initialized successfully.')\n} catch (error) {\n if (error instanceof z.ZodError) {\n const msg = JSON.stringify(error.format(), null, 2)\n logger.error(msg)\n } else {\n logger.error('Failed to initialize Shopify API client:', error)\n }\n throw error\n}\n\nexport { shopifyGraphqlClient as shopifyClient }\n","import { ApiVersion } from '@shopify/shopify-api'\n\n// https://shopify.dev/docs/api/admin-graphql/2025-04/\nexport const SHOPIFY_API_VERSION = ApiVersion.April25\n","import { logger } from './logger.js'\nimport { shopifyClient } from './shopifyClient.js'\n\nexport function convertIdIntoGid(\n id: bigint,\n type: 'Order' | 'Customer' | 'Fulfillment',\n): string {\n return `gid://shopify/${type}/${id}`\n}\n\ninterface PageInfo {\n hasNextPage: boolean\n endCursor?: string | null | undefined\n}\n\ninterface ShopifyErrorWithMessage {\n message?: string\n [key: string]: unknown\n}\n\nexport interface ShopifyUserErrorDetail {\n code?: string | null\n field?: string[] | null\n message?: string | null\n}\n\n/**\n * Custom error class for Shopify mutation userErrors.\n * Preserves the full error array so callers can inspect specific error codes.\n *\n * @example\n * try {\n * await cancelOrderById(orderId)\n * } catch (error) {\n * if (error instanceof ShopifyUserError) {\n * const alreadyCancelled = error.errors.some(e => e.code === 'ORDER_ALREADY_CANCELLED')\n * if (alreadyCancelled) { ... }\n * }\n * }\n */\nexport class ShopifyUserError extends Error {\n readonly errors: ShopifyUserErrorDetail[]\n\n constructor(message: string, errors: ShopifyUserErrorDetail[]) {\n super(message)\n this.name = 'ShopifyUserError'\n this.errors = errors\n }\n}\n\ntype TExtractorFunctionType<TResultNode, TPageData> = (pageData: TPageData) => {\n nodes: TResultNode[]\n pageInfo?: PageInfo\n userErrors?: ShopifyUserErrorDetail[]\n}\n\nexport async function fetchShopifyGraphql<TResultNode, TPageData>(params: {\n query: string\n variables: Record<string, unknown>\n dataExtractor?: TExtractorFunctionType<TResultNode, TPageData>\n fetchAllPages?: boolean\n}): Promise<TResultNode[]>\nexport async function fetchShopifyGraphql<TReturnType>(params: {\n query: string\n variables: Record<string, unknown>\n}): Promise<TReturnType>\nexport async function fetchShopifyGraphql<\n TResultNode,\n TPageData,\n TReturnType,\n>(params: {\n query: string\n variables: Record<string, unknown>\n dataExtractor?: TExtractorFunctionType<TResultNode, TPageData>\n fetchAllPages?: boolean\n}): Promise<TResultNode[] | TReturnType> {\n const {\n query,\n variables: initialVariables,\n dataExtractor,\n fetchAllPages = false,\n } = params\n\n let currentVariables = { ...initialVariables }\n\n if (!dataExtractor) {\n return makeRequest<NonNullable<TReturnType>>(query, currentVariables)\n }\n\n const allNodes: TResultNode[] = []\n let hasNextLoop = true\n\n do {\n const response = await makeRequest<TPageData>(query, currentVariables)\n const { nodes, pageInfo, userErrors } = dataExtractor(response)\n\n // Handle Shopify mutation userErrors pattern\n if (Array.isArray(userErrors) && userErrors.length > 0) {\n const errorMessages = userErrors\n .map((e) => e.message || JSON.stringify(e))\n .join('\\n')\n logger.error('Shopify mutation userErrors:', errorMessages)\n throw new ShopifyUserError(\n `Shopify mutation userErrors: ${errorMessages}`,\n userErrors,\n )\n }\n\n allNodes.push(...nodes)\n\n hasNextLoop = fetchAllPages ? !!pageInfo?.hasNextPage : false\n if (hasNextLoop && pageInfo?.endCursor) {\n currentVariables = {\n ...currentVariables,\n after: pageInfo.endCursor,\n }\n }\n } while (hasNextLoop)\n\n return allNodes\n}\n\nasync function makeRequest<TReturnDataType>(\n query: string,\n variables: Record<string, unknown>,\n): Promise<NonNullable<TReturnDataType>> {\n type ShopifyRequestErrorType = {\n errors?: ShopifyErrorWithMessage | ShopifyErrorWithMessage[]\n }\n\n const response = (await shopifyClient.request<TReturnDataType>(query, {\n variables,\n })) as { data?: TReturnDataType } & ShopifyRequestErrorType\n\n if (response.errors) {\n let errorMessages = 'GraphQL query failed.'\n const errors = response.errors\n if (Array.isArray(errors)) {\n errorMessages = errors\n .map((e: ShopifyErrorWithMessage) => e.message || JSON.stringify(e))\n .join('\\n')\n } else if (\n typeof errors === 'object' &&\n errors !== null &&\n 'message' in errors\n ) {\n errorMessages = errors.message || JSON.stringify(errors)\n } else if (typeof errors === 'string') {\n errorMessages = errors\n } else {\n errorMessages = JSON.stringify(errors)\n }\n logger.error('GraphQL query failed:', errorMessages)\n throw new Error(`GraphQL errors: ${errorMessages}`)\n }\n\n if (!response.data) {\n throw new Error('No data in Shopify API response')\n }\n\n return response.data\n}\n","import type {\n CustomerDeleteMutation,\n CustomerDeleteMutationVariables,\n} from '../../generated-api-types/2025-04/admin.generated'\nimport { gql } from '../../utils/logger'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch'\n\ntype SingleNode = { deletedCustomerId: string | null }\n\n/**\n * Deletes a customer from Shopify by their ID.\n * @param customerId - The customer ID (GID string, e.g., \"gid://shopify/Customer/123\")\n * @returns The deleted customer ID, or null if not found\n * @throws ShopifyUserError if Shopify returns user errors\n */\nexport async function deleteCustomerById(\n customerId: string,\n): Promise<string | undefined> {\n const mutation = gql`#graphql\n mutation customerDelete($input: CustomerDeleteInput!) {\n customerDelete(input: $input) {\n deletedCustomerId\n userErrors {\n field\n message\n }\n }\n }\n `\n\n const variables: CustomerDeleteMutationVariables = {\n input: { id: customerId },\n }\n\n const response = await fetchShopifyGraphql<\n SingleNode,\n CustomerDeleteMutation\n >({\n query: mutation,\n variables,\n dataExtractor: (data: CustomerDeleteMutation) => {\n if (!data.customerDelete) {\n throw new Error(\"GraphQL response missing 'customerDelete' field\")\n }\n return {\n nodes: [\n { deletedCustomerId: data.customerDelete.deletedCustomerId ?? null },\n ],\n userErrors: data.customerDelete.userErrors,\n }\n },\n })\n\n return response[0]?.deletedCustomerId ?? undefined\n}\n","import type {\n FileDeleteMutation,\n FileDeleteMutationVariables,\n} from '../../generated-api-types/2025-04/admin.generated'\nimport { gql } from '../../utils/logger'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch'\n\ntype SingleNode = { deletedFileIds: string[] }\n\n/**\n * Deletes files from Shopify by their IDs.\n * @param fileIds - Array of file IDs to delete (e.g., \"gid://shopify/MediaImage/123\")\n * @returns Array of successfully deleted file IDs\n * @throws ShopifyUserError if Shopify returns user errors\n */\nexport async function deleteFilesByIds(fileIds: string[]): Promise<string[]> {\n if (fileIds.length === 0) {\n return []\n }\n\n const mutation = gql`#graphql\n mutation fileDelete($fileIds: [ID!]!) {\n fileDelete(fileIds: $fileIds) {\n deletedFileIds\n userErrors {\n code\n field\n message\n }\n }\n }\n `\n\n const variables: FileDeleteMutationVariables = { fileIds }\n\n const response = await fetchShopifyGraphql<SingleNode, FileDeleteMutation>({\n query: mutation,\n variables,\n dataExtractor: (data: FileDeleteMutation) => {\n if (!data.fileDelete) {\n throw new Error(\"GraphQL response missing 'fileDelete' field\")\n }\n return {\n nodes: [{ deletedFileIds: data.fileDelete.deletedFileIds ?? [] }],\n userErrors: data.fileDelete.userErrors,\n }\n },\n })\n\n return response[0]?.deletedFileIds ?? []\n}\n","import type {\n CreateFileMutation,\n CreateFileMutationVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { gql, logger } from '../../utils/logger.js'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch.js'\n\nconst mutation = gql`#graphql\n mutation createFile($files: [FileCreateInput!]!) {\n fileCreate(files: $files) {\n files {\n id\n }\n userErrors {\n code\n field\n message\n }\n }\n }\n`\n\n/**\n * Creates a file in Shopify from an external URL.\n *\n * @param url - The HTTPS URL of the file to upload (must be publicly accessible)\n * @param altText - Alt text description for accessibility\n * @param filename - The filename to use in Shopify\n * @returns Promise resolving to the created file ID\n * @throws {Error} When the URL doesn't start with https://\n * @throws {ShopifyUserError} When the mutation fails\n *\n * @example\n * const fileId = await createFile(\n * 'https://example.com/image.png',\n * 'Product image',\n * 'product-image.png'\n * )\n */\nexport async function createFile(\n url: string,\n altText: string,\n filename: string,\n): Promise<string> {\n if (!url.startsWith('https://')) {\n throw new Error(\n `Not a valid public URL (https://) provided for file (url: ${url}).`,\n )\n }\n\n logger.debug(`Creating file: ${filename}`)\n\n const variables: CreateFileMutationVariables = {\n files: [\n {\n originalSource: url,\n alt: altText,\n filename: filename,\n },\n ],\n }\n\n const result = await fetchShopifyGraphql<{ id: string }, CreateFileMutation>({\n query: mutation,\n variables,\n dataExtractor: (data) => {\n if (!data.fileCreate) {\n throw new Error(\"GraphQL response missing 'fileCreate' field\")\n }\n\n const file = data.fileCreate.files?.[0]\n return {\n nodes: file ? [{ id: file.id }] : [],\n userErrors: data.fileCreate.userErrors,\n }\n },\n })\n\n const fileId = result[0]?.id\n if (!fileId) {\n throw new Error('File creation returned no result')\n }\n\n logger.debug(`Successfully created file ${fileId}`)\n\n return fileId\n}\n","import type {\n CreateMetaobjectDefinitionMutation,\n CreateMetaobjectDefinitionMutationVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { gql, logger } from '../../utils/logger.js'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch.js'\n\nexport type MetaobjectFieldDefinition = {\n key: string\n name?: string\n type: string\n description?: string\n required?: boolean\n}\n\nexport type CreateMetaobjectDefinitionInput = {\n type: string\n name?: string\n description?: string\n displayNameKey?: string\n fieldDefinitions: MetaobjectFieldDefinition[]\n}\n\nexport type CreateMetaobjectDefinitionResult = {\n id: string\n name: string\n type: string\n}\n\nconst mutation = gql`#graphql\n mutation createMetaobjectDefinition($definition: MetaobjectDefinitionCreateInput!) {\n metaobjectDefinitionCreate(definition: $definition) {\n metaobjectDefinition {\n id\n name\n type\n }\n userErrors {\n code\n field\n message\n }\n }\n }\n`\n\n/**\n * Creates a metaobject definition in Shopify.\n *\n * @param input - The metaobject definition input\n * @returns Promise resolving to the created metaobject definition\n * @throws {ShopifyUserError} When the mutation fails\n * @throws {Error} When GraphQL errors occur\n *\n * @example\n * await createMetaobjectDefinition({\n * type: 'my_custom_type',\n * name: 'My Custom Type',\n * description: 'A custom metaobject definition',\n * fieldDefinitions: [\n * { key: 'title', name: 'Title', type: 'single_line_text_field' },\n * { key: 'description', name: 'Description', type: 'multi_line_text_field' },\n * ],\n * })\n */\nexport async function createMetaobjectDefinition(\n input: CreateMetaobjectDefinitionInput,\n): Promise<CreateMetaobjectDefinitionResult> {\n logger.debug(`Creating metaobject definition with type: ${input.type}`)\n\n const variables: CreateMetaobjectDefinitionMutationVariables = {\n definition: {\n type: input.type,\n name: input.name,\n description: input.description,\n displayNameKey: input.displayNameKey,\n fieldDefinitions: input.fieldDefinitions,\n },\n }\n\n const result = await fetchShopifyGraphql<\n CreateMetaobjectDefinitionResult,\n CreateMetaobjectDefinitionMutation\n >({\n query: mutation,\n variables,\n dataExtractor: (data) => {\n if (!data.metaobjectDefinitionCreate) {\n throw new Error(\n \"GraphQL response missing 'metaobjectDefinitionCreate' field\",\n )\n }\n\n const metaobjectDefinition =\n data.metaobjectDefinitionCreate.metaobjectDefinition\n\n if (!metaobjectDefinition) {\n return {\n nodes: [],\n userErrors: data.metaobjectDefinitionCreate.userErrors,\n }\n }\n\n return {\n nodes: [\n {\n id: metaobjectDefinition.id,\n name: metaobjectDefinition.name,\n type: metaobjectDefinition.type,\n },\n ],\n userErrors: data.metaobjectDefinitionCreate.userErrors,\n }\n },\n })\n\n const definitionResult = result[0]\n if (!definitionResult) {\n throw new Error('Metaobject definition creation returned no result')\n }\n\n logger.debug(\n `Successfully created metaobject definition ${definitionResult.id}`,\n )\n\n return definitionResult\n}\n","import type {\n CreateFulfillmentMutation,\n CreateFulfillmentMutationVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { gql, logger } from '../../utils/logger.js'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch.js'\n\nexport type FulfillmentLineItem = {\n id: number | bigint | string\n quantity: number\n}\n\nexport type CreateFulfillmentResult = {\n id: string\n status: string\n trackingInfo: {\n company: string | null\n number: string | null\n }[]\n}\n\nconst mutation = gql`#graphql\n mutation createFulfillment($fulfillment: FulfillmentInput!) {\n fulfillmentCreate(fulfillment: $fulfillment) {\n fulfillment {\n id\n status\n trackingInfo {\n company\n number\n }\n }\n userErrors {\n field\n message\n }\n }\n }\n`\n\nfunction toGid(id: number | bigint | string, type: string): string {\n if (typeof id === 'string' && id.startsWith('gid://')) {\n return id\n }\n return `gid://shopify/${type}/${id}`\n}\n\n/**\n * Creates a fulfillment for a fulfillment order with optional tracking info.\n *\n * @param fulfillmentOrderId - The fulfillment order ID (numeric, bigint, or GID string)\n * @param fulfillmentOrderLineItems - Line items to fulfill with their quantities\n * @param options - Optional tracking and notification settings\n * @returns Promise resolving to the created fulfillment\n * @throws {ShopifyUserError} When the mutation fails\n * @throws {Error} When GraphQL errors occur\n *\n * @example\n * // Fulfill specific line items without tracking\n * await createFulfillment(123456789, [{ id: 111, quantity: 2 }])\n *\n * // Fulfill all items without tracking\n * await createFulfillment(123456789, [])\n *\n * // Fulfill with tracking info\n * await createFulfillment(\n * 123456789,\n * [{ id: 111, quantity: 2 }],\n * { trackingNumber: 'TRACK123', carrier: 'DHL', notifyCustomer: true }\n * )\n */\nexport async function createFulfillment(\n fulfillmentOrderId: number | bigint | string,\n fulfillmentOrderLineItems: FulfillmentLineItem[],\n options: {\n trackingNumber?: string\n carrier?: string\n trackingUrl?: string\n notifyCustomer?: boolean\n } = {},\n): Promise<CreateFulfillmentResult> {\n const {\n trackingNumber,\n carrier,\n trackingUrl,\n notifyCustomer = true,\n } = options\n\n const fulfillmentOrderGid = toGid(fulfillmentOrderId, 'FulfillmentOrder')\n\n logger.debug(`Creating fulfillment for order ${fulfillmentOrderGid}`)\n\n const lineItems = fulfillmentOrderLineItems.map((item) => ({\n id: toGid(item.id, 'FulfillmentOrderLineItem'),\n quantity: item.quantity,\n }))\n\n const variables: CreateFulfillmentMutationVariables = {\n fulfillment: {\n lineItemsByFulfillmentOrder: [\n {\n fulfillmentOrderId: fulfillmentOrderGid,\n ...(lineItems.length > 0\n ? { fulfillmentOrderLineItems: lineItems }\n : {}),\n },\n ],\n notifyCustomer,\n ...(trackingNumber\n ? {\n trackingInfo: {\n number: trackingNumber,\n ...(carrier ? { company: carrier } : {}),\n ...(trackingUrl ? { url: trackingUrl } : {}),\n },\n }\n : {}),\n },\n }\n\n const result = await fetchShopifyGraphql<\n CreateFulfillmentResult,\n CreateFulfillmentMutation\n >({\n query: mutation,\n variables,\n dataExtractor: (data) => {\n if (!data.fulfillmentCreate) {\n throw new Error(\"GraphQL response missing 'fulfillmentCreate' field\")\n }\n\n const fulfillment = data.fulfillmentCreate.fulfillment\n if (!fulfillment) {\n return {\n nodes: [],\n userErrors: data.fulfillmentCreate.userErrors,\n }\n }\n\n return {\n nodes: [\n {\n id: fulfillment.id,\n status: fulfillment.status,\n trackingInfo: fulfillment.trackingInfo.map((info) => ({\n company: info.company ?? null,\n number: info.number ?? null,\n })),\n },\n ],\n userErrors: data.fulfillmentCreate.userErrors,\n }\n },\n })\n\n const fulfillmentResult = result[0]\n if (!fulfillmentResult) {\n throw new Error('Fulfillment creation returned no result')\n }\n\n logger.debug(`Successfully created fulfillment ${fulfillmentResult.id}`)\n\n return fulfillmentResult\n}\n","import { gql } from '../../utils/logger'\n\nexport const queryFulfillmentTrackingIds = gql`#graphql\n query fulfillmentTrackingIds($id: ID!) {\n fulfillment(id: $id) {\n id\n trackingInfo(first: 50) {\n company\n number\n }\n }\n }\n`\n","import type {\n FulfillmentTrackingIdsQuery,\n FulfillmentTrackingIdsQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { logger } from '../../utils/logger.js'\nimport {\n convertIdIntoGid,\n fetchShopifyGraphql,\n} from '../../utils/shopifyFetch.js'\nimport { queryFulfillmentTrackingIds } from './getFulfillmentTrackingIds.queries.js'\n\nexport type FulfillmentTrackingIds = {\n trackingNumbers: string[]\n trackingCompany: string | null\n}\n\n/**\n * Retrieves tracking information for a fulfillment by its ID.\n * Returns the tracking numbers and the tracking company.\n *\n * @param {string | number | bigint} id - The Shopify fulfillment ID. Can be a GID string (e.g., \"gid://shopify/Fulfillment/123456789\") or a numeric ID (e.g., 123456789 or 123456789n).\n * @returns {Promise<FulfillmentTrackingIds | undefined>} A promise that resolves to the tracking info or undefined if fulfillment not found.\n * @throws {Error} If the GraphQL query fails.\n */\nexport async function getFulfillmentTrackingIds(\n id: string | number | bigint,\n): Promise<FulfillmentTrackingIds | undefined> {\n const gid =\n typeof id === 'string'\n ? id\n : convertIdIntoGid(\n typeof id === 'number' ? BigInt(id) : id,\n 'Fulfillment',\n )\n\n const variables: FulfillmentTrackingIdsQueryVariables = { id: gid }\n\n const response = await fetchShopifyGraphql<FulfillmentTrackingIdsQuery>({\n query: queryFulfillmentTrackingIds,\n variables,\n })\n\n if (!response.fulfillment) {\n logger.debug(`No fulfillment found with ID: ${id}`)\n return undefined\n }\n\n const trackingInfo = response.fulfillment.trackingInfo\n const trackingNumbers = trackingInfo\n .map((info) => info.number)\n .filter((num): num is string => num != null)\n // Use the first company found (typically all tracking numbers share the same company)\n const trackingCompany = trackingInfo[0]?.company ?? null\n\n return {\n trackingNumbers,\n trackingCompany,\n }\n}\n","import type {\n UpdateFulfillmentTrackingMutation,\n UpdateFulfillmentTrackingMutationVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { getFulfillmentTrackingIds } from '../../queries/fulfillments/getFulfillmentTrackingIds.js'\nimport { gql, logger } from '../../utils/logger.js'\nimport {\n convertIdIntoGid,\n fetchShopifyGraphql,\n} from '../../utils/shopifyFetch.js'\n\nexport type UpdateFulfillmentTrackingResult = {\n trackingNumbers: string[]\n trackingCompany: string | null\n}\n\nconst mutation = gql`#graphql\n mutation updateFulfillmentTracking(\n $fulfillmentId: ID!\n $trackingNumbers: [String!]!\n $company: String\n $notifyCustomer: Boolean\n ) {\n fulfillmentTrackingInfoUpdate(\n fulfillmentId: $fulfillmentId\n trackingInfoInput: { numbers: $trackingNumbers, company: $company }\n notifyCustomer: $notifyCustomer\n ) {\n fulfillment {\n trackingInfo {\n number\n company\n }\n }\n userErrors {\n field\n message\n }\n }\n }\n`\n\n/**\n * Adds a tracking number to an existing fulfillment.\n * Fetches existing tracking info and appends the new tracking number.\n *\n * @param fulfillmentId - The fulfillment ID (numeric, bigint, or GID string)\n * @param trackingNumber - The new tracking number to add\n * @param notifyCustomer - Whether to notify the customer (default: false)\n * @returns Promise resolving to the updated tracking info\n * @throws {ShopifyUserError} When the mutation fails\n * @throws {Error} When fulfillment not found or GraphQL errors occur\n *\n * @example\n * // Add tracking to fulfillment, don't notify customer yet\n * await updateFulfillmentTracking(123456789, 'TRACK123')\n *\n * // Add tracking and notify customer (e.g., last item in order)\n * await updateFulfillmentTracking(123456789, 'TRACK456', true)\n */\nexport async function updateFulfillmentTracking(\n fulfillmentId: number | bigint | string,\n trackingNumber: string,\n notifyCustomer = false,\n): Promise<UpdateFulfillmentTrackingResult> {\n const fulfillmentGid =\n typeof fulfillmentId === 'string'\n ? fulfillmentId\n : convertIdIntoGid(\n typeof fulfillmentId === 'number'\n ? BigInt(fulfillmentId)\n : fulfillmentId,\n 'Fulfillment',\n )\n\n logger.debug(`Updating tracking for fulfillment ${fulfillmentGid}`)\n\n const existingTracking = await getFulfillmentTrackingIds(fulfillmentGid)\n\n if (!existingTracking) {\n throw new Error(`Fulfillment not found: ${fulfillmentGid}`)\n }\n\n const updatedTrackingNumbers = existingTracking.trackingNumbers.includes(\n trackingNumber,\n )\n ? existingTracking.trackingNumbers\n : [...existingTracking.trackingNumbers, trackingNumber]\n\n const variables: UpdateFulfillmentTrackingMutationVariables = {\n fulfillmentId: fulfillmentGid,\n trackingNumbers: updatedTrackingNumbers,\n ...(existingTracking.trackingCompany\n ? { company: existingTracking.trackingCompany }\n : {}),\n notifyCustomer,\n }\n\n const result = await fetchShopifyGraphql<\n UpdateFulfillmentTrackingResult,\n UpdateFulfillmentTrackingMutation\n >({\n query: mutation,\n variables,\n dataExtractor: (data) => {\n if (!data.fulfillmentTrackingInfoUpdate) {\n throw new Error(\n \"GraphQL response missing 'fulfillmentTrackingInfoUpdate' field\",\n )\n }\n\n const fulfillment = data.fulfillmentTrackingInfoUpdate.fulfillment\n const trackingInfo = fulfillment?.trackingInfo ?? []\n const trackingNumbers = trackingInfo\n .map((info) => info.number)\n .filter((num): num is string => num != null)\n const trackingCompany = trackingInfo[0]?.company ?? null\n\n return {\n nodes: [{ trackingNumbers, trackingCompany }],\n userErrors: data.fulfillmentTrackingInfoUpdate.userErrors,\n }\n },\n })\n\n const trackingResult = result[0]\n if (!trackingResult) {\n throw new Error('Unexpected empty result from GraphQL mutation')\n }\n\n logger.debug(\n `Successfully updated tracking for fulfillment ${fulfillmentGid}`,\n )\n\n return trackingResult\n}\n","import type {\n OrderCancelMutation,\n OrderCancelMutationVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { gql, logger } from '../../utils/logger.js'\nimport {\n convertIdIntoGid,\n fetchShopifyGraphql,\n} from '../../utils/shopifyFetch.js'\n\ntype CancelOrderNode = { success: true }\n\nconst mutation = gql`#graphql\n mutation orderCancel($orderId: ID!) {\n orderCancel(\n orderId: $orderId\n refund: true\n restock: false\n reason: CUSTOMER\n notifyCustomer: true\n ) {\n orderCancelUserErrors {\n code\n field\n message\n }\n }\n }\n`\n\n/**\n * Cancel an order in Shopify.\n *\n * @param orderId - The order ID (numeric, bigint, or GID string)\n * @returns Promise resolving to true on success\n * @throws {ShopifyUserError} When cancellation fails (e.g., ORDER_ALREADY_CANCELLED)\n *\n * @example\n * // Success case\n * await cancelOrderById(12345678901234)\n *\n * // Error handling\n * import { ShopifyUserError } from '@ehrenkind/shopify-lib'\n * try {\n * await cancelOrderById(orderId)\n * } catch (error) {\n * if (error instanceof ShopifyUserError) {\n * const alreadyCancelled = error.errors.some(e => e.code === 'ORDER_ALREADY_CANCELLED')\n * }\n * }\n */\nexport async function cancelOrderById(\n orderId: number | bigint | string,\n): Promise<boolean> {\n const orderGid =\n typeof orderId === 'string'\n ? orderId\n : convertIdIntoGid(\n typeof orderId === 'number' ? BigInt(orderId) : orderId,\n 'Order',\n )\n\n logger.debug(`Cancelling order ${orderGid}`)\n\n const variables: OrderCancelMutationVariables = { orderId: orderGid }\n\n await fetchShopifyGraphql<CancelOrderNode, OrderCancelMutation>({\n query: mutation,\n variables,\n dataExtractor: (data) => {\n if (!data.orderCancel) {\n throw new Error(\"GraphQL response missing 'orderCancel' field\")\n }\n return {\n nodes: [{ success: true }],\n userErrors: data.orderCancel.orderCancelUserErrors,\n }\n },\n })\n\n logger.debug(`Order ${orderGid} cancelled successfully`)\n return true\n}\n","import type {\n CreateRefundMutation,\n CreateRefundMutationVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport {\n type CurrencyCode,\n OrderTransactionKind,\n type RefundLineItemRestockType,\n} from '../../generated-api-types/2025-04/admin.types.js'\nimport { gql, logger } from '../../utils/logger.js'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch.js'\n\nexport type CreateRefundLineItem = {\n lineItemId: number | bigint | string\n quantity: number\n restockType?: 'NO_RESTOCK' | 'CANCEL' | 'RETURN'\n locationId?: number | bigint | string\n}\n\nexport type CreateRefundTransaction = {\n amount: string\n gateway: string\n parentId?: number | bigint | string\n}\n\nexport type CreateRefundOptions = {\n currency?: CurrencyCode\n note?: string\n notify?: boolean\n refundLineItems?: CreateRefundLineItem[]\n shipping?: {\n fullRefund?: boolean\n amount?: string\n }\n transactions?: CreateRefundTransaction[]\n}\n\nexport type RefundMoney = {\n amount: string\n currencyCode: string\n}\n\nexport type CreateRefundResult = {\n id: string\n totalRefunded: {\n shopMoney: RefundMoney\n presentmentMoney: RefundMoney\n }\n}\n\nconst mutation = gql`#graphql\n mutation createRefund($input: RefundInput!) {\n refundCreate(input: $input) {\n refund {\n id\n totalRefundedSet {\n shopMoney {\n amount\n currencyCode\n }\n presentmentMoney {\n amount\n currencyCode\n }\n }\n }\n userErrors {\n field\n message\n }\n }\n }\n`\n\nfunction toGid(id: number | bigint | string, type: string): string {\n if (typeof id === 'string' && id.startsWith('gid://')) {\n return id\n }\n return `gid://shopify/${type}/${id}`\n}\n\n/**\n * Creates a refund for an order.\n *\n * @param orderId - The order ID (numeric, bigint, or GID string)\n * @param options - Refund configuration options\n * @returns Promise resolving to the created refund\n * @throws {ShopifyUserError} When the mutation fails\n * @throws {Error} When GraphQL errors occur\n *\n * @example\n * await createRefund(12345678901234, {\n * currency: 'EUR',\n * notify: true,\n * note: 'Customer return',\n * refundLineItems: [\n * { lineItemId: 111, quantity: 1, restockType: 'NO_RESTOCK' }\n * ],\n * transactions: [\n * { amount: '25.00', gateway: 'shopify_payments', parentId: 222 }\n * ]\n * })\n */\nexport async function createRefund(\n orderId: number | bigint | string,\n options: CreateRefundOptions = {},\n): Promise<CreateRefundResult> {\n const { currency, note, notify, refundLineItems, shipping, transactions } =\n options\n\n const orderGid = toGid(orderId, 'Order')\n\n logger.debug(`Creating refund for order ${orderGid}`)\n\n const variables: CreateRefundMutationVariables = {\n input: {\n orderId: orderGid,\n notify,\n ...(currency ? { currency } : {}),\n ...(note ? { note } : {}),\n ...(refundLineItems?.length\n ? {\n refundLineItems: refundLineItems.map((item) => ({\n lineItemId: toGid(item.lineItemId, 'LineItem'),\n quantity: item.quantity,\n ...(item.restockType\n ? { restockType: item.restockType as RefundLineItemRestockType }\n : {}),\n ...(item.locationId\n ? { locationId: toGid(item.locationId, 'Location') }\n : {}),\n })),\n }\n : {}),\n ...(shipping\n ? {\n shipping: {\n ...(shipping.fullRefund !== undefined\n ? { fullRefund: shipping.fullRefund }\n : {}),\n ...(shipping.amount ? { amount: shipping.amount } : {}),\n },\n }\n : {}),\n ...(transactions?.length\n ? {\n transactions: transactions.map((t) => ({\n amount: t.amount,\n gateway: t.gateway,\n kind: OrderTransactionKind.Refund,\n orderId: orderGid,\n ...(t.parentId\n ? { parentId: toGid(t.parentId, 'OrderTransaction') }\n : {}),\n })),\n }\n : {}),\n },\n }\n\n const result = await fetchShopifyGraphql<\n CreateRefundResult,\n CreateRefundMutation\n >({\n query: mutation,\n variables,\n dataExtractor: (data) => {\n if (!data.refundCreate) {\n throw new Error(\"GraphQL response missing 'refundCreate' field\")\n }\n\n const refund = data.refundCreate.refund\n if (!refund) {\n return {\n nodes: [],\n userErrors: data.refundCreate.userErrors,\n }\n }\n\n return {\n nodes: [\n {\n id: refund.id,\n totalRefunded: {\n shopMoney: {\n amount: refund.totalRefundedSet.shopMoney.amount,\n currencyCode: refund.totalRefundedSet.shopMoney.currencyCode,\n },\n presentmentMoney: {\n amount: refund.totalRefundedSet.presentmentMoney.amount,\n currencyCode:\n refund.totalRefundedSet.presentmentMoney.currencyCode,\n },\n },\n },\n ],\n userErrors: data.refundCreate.userErrors,\n }\n },\n })\n\n const refundResult = result[0]\n if (!refundResult) {\n throw new Error('Refund creation returned no result')\n }\n\n logger.debug(`Successfully created refund ${refundResult.id}`)\n\n return refundResult\n}\n","import type {\n BulkUpdateProductVariantsMutation,\n BulkUpdateProductVariantsMutationVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport type { ProductVariantsBulkInput } from '../../generated-api-types/2025-04/admin.types.js'\nimport { gql, logger } from '../../utils/logger.js'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch.js'\n\nexport type VariantUpdateInput = Omit<ProductVariantsBulkInput, 'id'> & {\n id: string\n}\n\nexport type BulkUpdateProductVariantsResult = {\n id: string\n sku: string | null\n}\n\nconst mutation = gql`#graphql\n mutation bulkUpdateProductVariants(\n $productId: ID!\n $variants: [ProductVariantsBulkInput!]!\n ) {\n productVariantsBulkUpdate(\n productId: $productId\n variants: $variants\n ) {\n productVariants {\n id\n sku\n }\n userErrors {\n code\n field\n message\n }\n }\n }\n`\n\n/**\n * Bulk updates product variants.\n *\n * @param productId - The product GID\n * @param variants - Array of variant updates (id required, plus fields to update)\n * @returns Array of updated variants with id and sku\n * @throws {ShopifyUserError} When the mutation fails\n */\nexport async function bulkUpdateProductVariants(\n productId: string,\n variants: VariantUpdateInput[],\n): Promise<BulkUpdateProductVariantsResult[]> {\n logger.debug(\n `Bulk updating ${variants.length} variants for product ${productId}`,\n )\n\n const variables: BulkUpdateProductVariantsMutationVariables = {\n productId,\n variants,\n }\n\n const result = await fetchShopifyGraphql<\n BulkUpdateProductVariantsResult,\n BulkUpdateProductVariantsMutation\n >({\n query: mutation,\n variables,\n dataExtractor: (data) => {\n if (!data.productVariantsBulkUpdate) {\n throw new Error(\n \"GraphQL response missing 'productVariantsBulkUpdate' field\",\n )\n }\n\n return {\n nodes: (data.productVariantsBulkUpdate.productVariants ?? []).map(\n (v) => ({\n id: v.id,\n sku: v.sku ?? null,\n }),\n ),\n userErrors: data.productVariantsBulkUpdate.userErrors,\n }\n },\n })\n\n logger.debug(`Successfully updated ${result.length} variants`)\n\n return result\n}\n","import type {\n UpsertMetaobjectMutation,\n UpsertMetaobjectMutationVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport type { MetaobjectFieldInput } from '../../generated-api-types/2025-04/admin.types.js'\nimport { gql, logger } from '../../utils/logger.js'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch.js'\n\nexport type UpsertMetaobjectInput = {\n type: string\n handle: string\n fields: MetaobjectFieldInput[]\n}\n\nexport type UpsertMetaobjectResult = {\n id: string\n handle: string\n displayName: string\n fields: Array<{ key: string; value: string | null }>\n}\n\nconst mutation = gql`#graphql\n mutation upsertMetaobject(\n $handle: MetaobjectHandleInput!\n $metaobject: MetaobjectUpsertInput!\n ) {\n metaobjectUpsert(handle: $handle, metaobject: $metaobject) {\n metaobject {\n id\n handle\n displayName\n fields {\n key\n value\n }\n }\n userErrors {\n code\n field\n message\n }\n }\n }\n`\n\n/**\n * Creates or updates a metaobject in Shopify based on its type and handle.\n *\n * @param input - The metaobject type, handle, and fields\n * @returns The created/updated metaobject\n * @throws {ShopifyUserError} When the upsert fails due to validation errors\n * @throws {Error} When GraphQL errors occur or no metaobject is returned\n */\nexport async function upsertMetaobject(\n input: UpsertMetaobjectInput,\n): Promise<UpsertMetaobjectResult> {\n const { type, handle, fields } = input\n\n logger.debug(`Upserting metaobject type=${type} handle=${handle}`)\n\n const variables: UpsertMetaobjectMutationVariables = {\n handle: { type, handle },\n metaobject: { fields },\n }\n\n const response = await fetchShopifyGraphql<\n UpsertMetaobjectResult,\n UpsertMetaobjectMutation\n >({\n query: mutation,\n variables,\n dataExtractor: (data) => {\n if (!data.metaobjectUpsert) {\n throw new Error(\"GraphQL response missing 'metaobjectUpsert' field\")\n }\n const { metaobject, userErrors } = data.metaobjectUpsert\n return {\n nodes: metaobject\n ? [\n {\n id: metaobject.id,\n handle: metaobject.handle,\n displayName: metaobject.displayName,\n fields: metaobject.fields.map((f) => ({\n key: f.key,\n value: f.value ?? null,\n })),\n },\n ]\n : [],\n userErrors,\n }\n },\n })\n\n const result = response[0]\n if (!result) {\n throw new Error('No metaobject returned from upsert operation')\n }\n logger.debug(`Metaobject upserted successfully: ${result.id}`)\n return result\n}\n","import { gql } from '../../utils/logger'\n\nexport const querySuggestedRefund = gql`#graphql\n query suggestedRefund(\n $orderId: ID!\n $refundLineItems: [RefundLineItemInput!]\n $refundShipping: Boolean\n $shippingAmount: Money\n $suggestFullRefund: Boolean\n ) {\n order(id: $orderId) {\n id\n name\n suggestedRefund(\n refundLineItems: $refundLineItems\n refundShipping: $refundShipping\n shippingAmount: $shippingAmount\n suggestFullRefund: $suggestFullRefund\n ) {\n amountSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n maximumRefundableSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n subtotalSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n totalTaxSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n discountedSubtotalSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n totalCartDiscountAmountSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n shipping {\n amountSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n maximumRefundableSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n }\n refundLineItems {\n lineItem {\n id\n sku\n title\n quantity\n }\n quantity\n priceSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n subtotalSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n totalTaxSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n restockType\n }\n suggestedTransactions {\n gateway\n kind\n amountSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n maximumRefundableSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n parentTransaction {\n id\n }\n }\n }\n }\n }\n`\n","import type {\n SuggestedRefundQuery,\n SuggestedRefundQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { RefundLineItemRestockType } from '../../generated-api-types/2025-04/admin.types.js'\nimport { logger } from '../../utils/logger.js'\nimport {\n convertIdIntoGid,\n fetchShopifyGraphql,\n} from '../../utils/shopifyFetch.js'\nimport { querySuggestedRefund } from './calculateRefund.queries.js'\n\n// Derive type from GraphQL response\nexport type SuggestedRefund = NonNullable<\n NonNullable<SuggestedRefundQuery['order']>['suggestedRefund']\n>\n\nexport interface CalculateRefundLineItem {\n lineItemId: number | bigint | string\n quantity: number\n restockType?: 'NO_RESTOCK' | 'CANCEL' | 'RETURN'\n locationId?: string\n}\n\nexport interface CalculateRefundOptions {\n refundLineItems?: CalculateRefundLineItem[]\n refundShipping?: boolean\n shippingAmount?: string\n suggestFullRefund?: boolean\n}\n\nfunction convertLineItemIdToGid(id: number | bigint | string): string {\n if (typeof id === 'string') {\n return id.startsWith('gid://') ? id : `gid://shopify/LineItem/${id}`\n }\n return `gid://shopify/LineItem/${id}`\n}\n\nfunction mapRestockType(\n restockType: 'NO_RESTOCK' | 'CANCEL' | 'RETURN' | undefined,\n): RefundLineItemRestockType {\n switch (restockType) {\n case 'CANCEL':\n return RefundLineItemRestockType.Cancel\n case 'RETURN':\n return RefundLineItemRestockType.Return\n default:\n return RefundLineItemRestockType.NoRestock\n }\n}\n\n/**\n * Calculate a suggested refund for an order.\n * Returns undefined if the order is not found or has no refundable items.\n *\n * @param orderId - The order ID (numeric, bigint, or GID string)\n * @param options - Options for the refund calculation\n * @returns The suggested refund or undefined\n */\nexport async function calculateRefund(\n orderId: number | bigint | string,\n options: CalculateRefundOptions = {},\n): Promise<SuggestedRefund | undefined> {\n const orderGid =\n typeof orderId === 'string'\n ? orderId\n : convertIdIntoGid(\n typeof orderId === 'number' ? BigInt(orderId) : orderId,\n 'Order',\n )\n\n const variables: SuggestedRefundQueryVariables = {\n orderId: orderGid,\n refundLineItems: options.refundLineItems?.map((item) => ({\n lineItemId: convertLineItemIdToGid(item.lineItemId),\n quantity: item.quantity,\n restockType: mapRestockType(item.restockType),\n ...(item.locationId ? { locationId: item.locationId } : {}),\n })),\n refundShipping: options.refundShipping,\n shippingAmount: options.shippingAmount,\n suggestFullRefund: options.suggestFullRefund,\n }\n\n const response = await fetchShopifyGraphql<SuggestedRefundQuery>({\n query: querySuggestedRefund,\n variables,\n })\n\n if (!response.order?.suggestedRefund) {\n logger.debug(`No refund suggestion available for order: ${orderId}`)\n return undefined\n }\n\n return response.order.suggestedRefund\n}\n","import z from 'zod'\nimport type {\n OrderByIdFullQuery,\n OrderByIdQuery,\n OrderByIdQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { logger } from '../../utils/logger.js'\nimport {\n convertIdIntoGid,\n fetchShopifyGraphql,\n} from '../../utils/shopifyFetch.js'\nimport { returnOutputParsed } from '../../utils/zod.js'\nimport { queryOrderById, queryOrderByIdFull } from './getOrderById.queries.js'\n\n// Address schema (shared between lean and full)\nconst AddressSchema = z\n .object({\n firstName: z.string().nullable(),\n lastName: z.string().nullable(),\n address1: z.string().nullable(),\n address2: z.string().nullable(),\n city: z.string().nullable(),\n province: z.string().nullable(),\n country: z.string().nullable(),\n zip: z.string().nullable(),\n })\n .nullable()\n\n// Lean order schema\nconst GetLeanOrderByIdReturn = z.object({\n id: z.string(),\n name: z.string(),\n createdAt: z.string(),\n updatedAt: z.string(),\n cancelledAt: z.string().nullable(),\n cancelReason: z.string().nullable(),\n totalPrice: z.object({\n amount: z.string(),\n currencyCode: z.string(),\n }),\n customer: z\n .object({\n id: z.string(),\n displayName: z.string(),\n firstName: z.string().nullable(),\n lastName: z.string().nullable(),\n emailAddress: z.string().nullable(),\n })\n .nullable(),\n financialStatus: z.string().nullable(),\n fulfillmentStatus: z.string().nullable(),\n shippingAddress: AddressSchema,\n})\n\nexport type LeanOrder = z.infer<typeof GetLeanOrderByIdReturn> | undefined\n\n// Full order type - derived from the generated GraphQL types\nexport type FullOrder = NonNullable<OrderByIdFullQuery['order']>\n\ntype OrderDetailLevel = 'lean' | 'full'\n\n// Function overloads\nexport function getOrderById(id: number | bigint): Promise<LeanOrder>\nexport function getOrderById(\n id: number | bigint,\n detailLevel: 'lean',\n): Promise<LeanOrder>\nexport function getOrderById(\n id: number | bigint,\n detailLevel: 'full',\n): Promise<FullOrder | undefined>\n\n/**\n * Retrieves a single order from Shopify by its numeric ID.\n * Returns undefined if no order is found with the specified ID.\n *\n * @param {number | bigint} id - The numerical Shopify order ID (e.g., 12345678 or 12345678n).\n * @param {OrderDetailLevel} detailLevel - The level of detail to return ('lean' or 'full'). Defaults to 'lean'.\n * @returns {Promise<LeanOrder | FullOrder>} A promise that resolves to the order data or undefined if not found.\n * @throws {Error} If the GraphQL query fails or if the response structure is invalid.\n */\nexport async function getOrderById(\n id: number | bigint,\n detailLevel: OrderDetailLevel = 'lean',\n): Promise<LeanOrder | FullOrder> {\n const bigIntId = typeof id === 'number' ? BigInt(id) : id\n if (detailLevel === 'lean') {\n return getLeanOrderById(bigIntId)\n }\n return getFullOrderById(bigIntId)\n}\n\nasync function getLeanOrderById(id: bigint): Promise<LeanOrder> {\n const variables: OrderByIdQueryVariables = {\n id: convertIdIntoGid(id, 'Order'),\n }\n\n const response = await fetchShopifyGraphql<OrderByIdQuery>({\n query: queryOrderById,\n variables,\n })\n\n if (!response.order) {\n logger.debug(`No order found with ID: ${id}`)\n return undefined\n }\n\n const order = response.order\n\n const leanOrder = {\n id: order.id,\n name: order.name,\n createdAt: order.createdAt,\n updatedAt: order.updatedAt,\n cancelledAt: order.cancelledAt ?? null,\n cancelReason: order.cancelReason ?? null,\n totalPrice: {\n amount: order.totalPriceSet?.shopMoney?.amount ?? '',\n currencyCode: order.totalPriceSet?.shopMoney?.currencyCode ?? '',\n },\n customer: order.customer\n ? {\n id: order.customer.id,\n displayName: order.customer.displayName,\n firstName: order.customer.firstName ?? null,\n lastName: order.customer.lastName ?? null,\n emailAddress:\n order.customer.defaultEmailAddress?.emailAddress ?? null,\n }\n : null,\n financialStatus: order.displayFinancialStatus ?? null,\n fulfillmentStatus: order.displayFulfillmentStatus ?? null,\n shippingAddress: order.shippingAddress\n ? {\n firstName: order.shippingAddress.firstName ?? null,\n lastName: order.shippingAddress.lastName ?? null,\n address1: order.shippingAddress.address1 ?? null,\n address2: order.shippingAddress.address2 ?? null,\n city: order.shippingAddress.city ?? null,\n province: order.shippingAddress.province ?? null,\n country: order.shippingAddress.country ?? null,\n zip: order.shippingAddress.zip ?? null,\n }\n : null,\n }\n\n return await returnOutputParsed(leanOrder, GetLeanOrderByIdReturn)\n}\n\nasync function getFullOrderById(id: bigint): Promise<FullOrder | undefined> {\n const variables: OrderByIdQueryVariables = {\n id: convertIdIntoGid(id, 'Order'),\n }\n\n const response = await fetchShopifyGraphql<OrderByIdFullQuery>({\n query: queryOrderByIdFull,\n variables,\n })\n\n if (!response.order) {\n logger.debug(`No order found with ID: ${id}`)\n return undefined\n }\n\n return response.order\n}\n","import z from 'zod'\nimport { logger } from './logger.js'\n\nexport async function returnOutputParsed<T>(\n data: unknown,\n Model: z.ZodType<T>,\n) {\n const parsed = await Model.safeParseAsync(data)\n if (!parsed.success) {\n if (parsed.error instanceof z.ZodError) {\n const msg = JSON.stringify(parsed.error.format(), null, 2)\n logger.error(msg)\n } else {\n logger.error('Failed to parse:', parsed.error)\n }\n // throw parsedVariants.error\n throw new Error('Failed to parse product variants')\n }\n logger.info('Parsed data successfully')\n return parsed.data\n}\n","import { gql } from '../../utils/logger'\n\nexport const queryOrderById = gql`#graphql\n query orderById($id: ID!) {\n order(id: $id) {\n id\n name\n createdAt\n updatedAt\n cancelledAt\n cancelReason\n totalPriceSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n customer {\n id\n lastName\n defaultEmailAddress {\n emailAddress\n }\n displayName\n firstName\n }\n displayFinancialStatus\n displayFulfillmentStatus\n shippingAddress {\n firstName\n lastName\n address1\n address2\n city\n province\n country\n zip\n }\n }\n }\n`\n\nexport const queryOrderByIdFull = gql`#graphql\n query orderByIdFull($id: ID!) {\n order(id: $id) {\n id\n name\n createdAt\n updatedAt\n processedAt\n closedAt\n cancelledAt\n cancelReason\n totalPriceSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n customer {\n id\n firstName\n lastName\n email\n phone\n }\n displayFinancialStatus\n displayFulfillmentStatus\n shippingAddress {\n firstName\n lastName\n address1\n address2\n city\n province\n country\n zip\n }\n billingAddress {\n firstName\n lastName\n address1\n address2\n city\n province\n country\n zip\n }\n lineItems(first: 100) {\n edges {\n node {\n id\n sku\n title\n variantTitle\n quantity\n customAttributes {\n key\n value\n }\n originalUnitPriceSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n vendor\n image {\n url\n width\n height\n altText\n }\n }\n }\n }\n fulfillments {\n id\n name\n totalQuantity\n status\n createdAt\n estimatedDeliveryAt\n deliveredAt\n trackingInfo {\n company\n number\n url\n }\n fulfillmentLineItems(first: 100) {\n edges {\n node {\n id\n quantity\n lineItem {\n id\n sku\n }\n }\n }\n }\n }\n shippingLine {\n originalPriceSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n }\n taxLines {\n priceSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n }\n totalDiscountsSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n discountCodes\n refunds {\n totalRefundedSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n }\n }\n }\n`\n","import z from 'zod'\nimport type {\n OrdersByNameFullQuery,\n OrdersByNameQuery,\n OrdersByNameQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { logger } from '../../utils/logger.js'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch.js'\nimport { returnOutputParsed } from '../../utils/zod.js'\nimport {\n queryOrdersByName,\n queryOrdersByNameFull,\n} from './getOrderByName.queries.js'\n\nconst GetLeanOrderByNameReturn = z.object({\n id: z.string(),\n name: z.string(),\n createdAt: z.string(),\n updatedAt: z.string(),\n totalPrice: z.object({\n amount: z.string(),\n currencyCode: z.string(),\n }),\n customer: z\n .object({\n id: z.string(),\n displayName: z.string(),\n emailAddress: z.string().nullable(),\n })\n .nullable(),\n financialStatus: z.string().nullable(),\n fulfillmentStatus: z.string().nullable(),\n})\n\nexport type LeanOrderByName =\n | z.infer<typeof GetLeanOrderByNameReturn>\n | undefined\n\nexport type FullOrderByName =\n | NonNullable<\n NonNullable<OrdersByNameFullQuery['orders']>['edges'][number]['node']\n >\n | undefined\n\ntype OrderDetailLevel = 'lean' | 'full'\n\n// Function overloads\nexport function getOrderByName(\n orderName: string,\n detailLevel: 'lean',\n): Promise<LeanOrderByName>\nexport function getOrderByName(\n orderName: string,\n detailLevel: 'full',\n): Promise<FullOrderByName>\nexport function getOrderByName(orderName: string): Promise<LeanOrderByName>\n\n/**\n * Retrieves a single order from Shopify by its order name (e.g., \"B12345\").\n * Returns undefined if no order is found with the specified name.\n *\n * @param {string} orderName - The order name to search for (e.g., \"B12345\").\n * @param {OrderDetailLevel} detailLevel - The level of detail to return ('lean' or 'full'). Defaults to 'lean'.\n * @returns {Promise<LeanOrderByName | FullOrderByName>} A promise that resolves to the order data or undefined if not found.\n * @throws {Error} If the GraphQL query fails or if the response structure is invalid.\n */\nexport async function getOrderByName(\n orderName: string,\n detailLevel: OrderDetailLevel = 'lean',\n): Promise<LeanOrderByName | FullOrderByName> {\n if (detailLevel === 'lean') {\n return getLeanOrderByName(orderName)\n }\n return getFullOrderByName(orderName)\n}\n\nasync function getLeanOrderByName(orderName: string): Promise<LeanOrderByName> {\n const variables: OrdersByNameQueryVariables = {\n first: 1,\n queryFilter: `name:${orderName}`,\n }\n\n type SingleNode = NonNullable<\n NonNullable<OrdersByNameQuery['orders']>['edges'][number]['node']\n >\n\n const extractedNodes = await fetchShopifyGraphql<\n SingleNode,\n OrdersByNameQuery\n >({\n query: queryOrdersByName,\n variables,\n dataExtractor: (pageData: OrdersByNameQuery) => {\n if (!pageData.orders) {\n throw new Error(\n \"GraphQL response for orders is missing the 'orders' field.\",\n )\n }\n const nodes: SingleNode[] = pageData.orders.edges.map(\n (edge: { node: SingleNode }) => edge.node,\n )\n return {\n nodes,\n }\n },\n fetchAllPages: false,\n })\n\n const order = extractedNodes[0]\n if (!order) {\n logger.debug(`No order found with name: ${orderName}`)\n return undefined\n }\n\n const leanOrder = {\n id: order.id,\n name: order.name,\n createdAt: order.createdAt,\n updatedAt: order.updatedAt,\n totalPrice: {\n amount: order.totalPriceSet?.shopMoney?.amount ?? '',\n currencyCode: order.totalPriceSet?.shopMoney?.currencyCode ?? '',\n },\n customer: order.customer\n ? {\n id: order.customer.id,\n displayName: order.customer.displayName,\n emailAddress:\n order.customer.defaultEmailAddress?.emailAddress ?? null,\n }\n : null,\n financialStatus: order.displayFinancialStatus ?? null,\n fulfillmentStatus: order.displayFulfillmentStatus ?? null,\n }\n\n return await returnOutputParsed(leanOrder, GetLeanOrderByNameReturn)\n}\n\nasync function getFullOrderByName(orderName: string): Promise<FullOrderByName> {\n const variables: OrdersByNameQueryVariables = {\n first: 1,\n queryFilter: `name:${orderName}`,\n }\n\n type SingleNode = NonNullable<\n NonNullable<OrdersByNameFullQuery['orders']>['edges'][number]['node']\n >\n\n const extractedNodes = await fetchShopifyGraphql<\n SingleNode,\n OrdersByNameFullQuery\n >({\n query: queryOrdersByNameFull,\n variables,\n dataExtractor: (pageData: OrdersByNameFullQuery) => {\n if (!pageData.orders) {\n throw new Error(\n \"GraphQL response for orders is missing the 'orders' field.\",\n )\n }\n const nodes: SingleNode[] = pageData.orders.edges.map(\n (edge: { node: SingleNode }) => edge.node,\n )\n return {\n nodes,\n }\n },\n fetchAllPages: false,\n })\n\n if (extractedNodes.length === 0) {\n logger.debug(`No order found with name: ${orderName}`)\n return undefined\n }\n\n const order = extractedNodes[0]\n if (!order) {\n logger.debug(`No order found with name: ${orderName}`)\n return undefined\n }\n\n return order\n}\n","import { gql } from '../../utils/logger'\n\nexport const queryOrdersByName = gql`#graphql\n query ordersByName($first: Int!, $queryFilter: String!) {\n orders(first: $first, query: $queryFilter) {\n edges {\n node {\n id\n name\n createdAt\n updatedAt\n totalPriceSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n customer {\n id\n lastName\n defaultEmailAddress {\n emailAddress\n }\n displayName\n firstName\n }\n displayFinancialStatus\n displayFulfillmentStatus\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n`\n\nexport const queryOrdersByNameFull = gql`#graphql\n query ordersByNameFull($first: Int!, $queryFilter: String!) {\n orders(first: $first, query: $queryFilter) {\n edges {\n node {\n billingAddress {\n address1\n address2\n city\n company\n country\n countryCodeV2\n firstName\n formattedArea\n id\n lastName\n name\n phone\n province\n provinceCode\n timeZone\n zip\n }\n billingAddressMatchesShippingAddress\n cancelReason\n cancellation {\n staffNote\n }\n cancelledAt\n capturable\n clientIp\n closed\n closedAt\n confirmed\n createdAt\n currencyCode\n currentCartDiscountAmountSet {\n presentmentMoney {\n amount\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n currentShippingPriceSet {\n presentmentMoney {\n amount\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n currentSubtotalLineItemsQuantity\n currentSubtotalPriceSet {\n presentmentMoney {\n amount\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n currentTaxLines {\n channelLiable\n rate\n ratePercentage\n source\n title\n priceSet {\n presentmentMoney {\n amount\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n }\n currentTotalAdditionalFeesSet {\n presentmentMoney {\n amount\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n currentTotalDiscountsSet {\n presentmentMoney {\n amount\n currencyCode\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n currentTotalDutiesSet {\n presentmentMoney {\n amount\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n currentTotalPriceSet {\n presentmentMoney {\n amount\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n currentTotalTaxSet {\n presentmentMoney {\n amount\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n currentTotalWeight\n customer {\n id\n lastName\n defaultEmailAddress {\n emailAddress\n }\n displayName\n firstName\n }\n customerAcceptsMarketing\n discountCodes\n discountCode\n displayAddress {\n address1\n address2\n city\n company\n country\n countryCodeV2\n firstName\n formattedArea\n id\n lastName\n name\n phone\n province\n provinceCode\n timeZone\n zip\n }\n displayFinancialStatus\n displayFulfillmentStatus\n dutiesIncluded\n edited\n email\n estimatedTaxes\n fulfillable\n fulfillments(first: 20) {\n createdAt\n deliveredAt\n displayStatus\n estimatedDeliveryAt\n updatedAt\n trackingInfo(first: 10) {\n company\n url\n }\n totalQuantity\n status\n name\n id\n }\n fullyPaid\n id\n lineItems(first: 50) {\n edges {\n node {\n id\n name\n originalUnitPriceSet {\n presentmentMoney {\n amount\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n quantity\n requiresShipping\n sku\n title\n variantTitle\n }\n }\n }\n name\n note\n processedAt\n shippingAddress {\n address1\n address2\n city\n company\n country\n countryCodeV2\n firstName\n formattedArea\n id\n lastName\n name\n phone\n province\n provinceCode\n timeZone\n zip\n }\n statusPageUrl\n tags\n totalPriceSet {\n presentmentMoney {\n amount\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n totalReceivedSet {\n presentmentMoney {\n amount\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n totalRefundedSet {\n presentmentMoney {\n amount\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n totalShippingPriceSet {\n presentmentMoney {\n amount\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n totalTaxSet {\n presentmentMoney {\n amount\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n totalWeight\n unpaid\n updatedAt\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n`\n","import { gql } from '../../utils/logger'\n\nexport const queryOrderCancellationInfoByName = gql`#graphql\n query orderCancellationInfoByName($first: Int!, $queryFilter: String!) {\n orders(first: $first, query: $queryFilter) {\n edges {\n node {\n id\n name\n cancelledAt\n }\n }\n }\n }\n`\n","import type {\n OrderCancellationInfoByNameQuery,\n OrderCancellationInfoByNameQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { logger } from '../../utils/logger.js'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch.js'\nimport { queryOrderCancellationInfoByName } from './getOrderCancellationInfo.queries.js'\n\n// OrderCancellationInfo type - derived from the generated GraphQL types\nexport type OrderCancellationInfo = NonNullable<\n OrderCancellationInfoByNameQuery['orders']['edges'][number]['node']\n>\n\n/**\n * Retrieves cancellation information for an order by its name (e.g., \"B12345\").\n * Returns undefined if no order is found with the specified name.\n *\n * @param {string} orderName - The order name to search for (e.g., \"B12345\").\n * @returns {Promise<OrderCancellationInfo | undefined>} A promise that resolves to the order cancellation info or undefined if not found.\n * @throws {Error} If the GraphQL query fails or if the response structure is invalid.\n */\nexport async function getOrderCancellationInfoByName(\n orderName: string,\n): Promise<OrderCancellationInfo | undefined> {\n const variables: OrderCancellationInfoByNameQueryVariables = {\n first: 1,\n queryFilter: `name:${orderName}`,\n }\n\n const response = await fetchShopifyGraphql<OrderCancellationInfoByNameQuery>({\n query: queryOrderCancellationInfoByName,\n variables,\n })\n\n if (!response.orders) {\n throw new Error(\n \"Invalid GraphQL response for getOrderCancellationInfoByName: 'orders' field is missing.\",\n )\n }\n\n if (!Array.isArray(response.orders.edges)) {\n throw new Error(\n \"Invalid GraphQL response for getOrderCancellationInfoByName: 'orders.edges' is not an array.\",\n )\n }\n\n const firstEdge = response.orders.edges[0]\n const order = firstEdge?.node\n\n if (!order) {\n logger.debug(`No order found with name: ${orderName}`)\n return undefined\n }\n\n return order\n}\n","import z from 'zod'\nimport type {\n LeanProductVariantsQuery,\n LeanProductVariantsQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { gql, logger } from '../../utils/logger.js'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch.js'\nimport { returnOutputParsed } from '../../utils/zod.js'\n\nconst GetLeanProductVariantsReturn = z.array(\n z.object({\n productId: z.string(),\n productTitle: z.string(),\n variantId: z.string(),\n variantTitle: z.string(),\n sku: z.string(),\n status: z.enum(['ACTIVE', 'ARCHIVED', 'DRAFT']),\n }),\n)\n\nexport type LeanProductVariant = z.infer<\n typeof GetLeanProductVariantsReturn\n>[number]\n\nexport type LeanProductVariantsOptions = {\n /** Filter to only active/draft products (excludes ARCHIVED). Defaults to false. */\n activeOnly?: boolean\n}\n\n/**\n * Retrieves a lean list of product variants from Shopify, optionally filtered by SKUs.\n * Product variants are mapped to a simpler output structure.\n * Variants missing essential properties (e.g., SKU) will be filtered out and logged.\n *\n * @param {string[]} [skus] - An optional array of SKUs to filter by. If provided, only variants matching these SKUs will be fetched.\n * @param {LeanProductVariantsOptions} [options] - Optional settings.\n * @param {boolean} [options.activeOnly=false] - If true, excludes ARCHIVED products at query level.\n * @returns {Promise<LeanProductVariant[]>} A promise that resolves to an array of lean product variant data.\n * @throws {Error} If the GraphQL query fails, returns no data, or if the `productVariants` field is missing in the response.\n */\nexport async function getLeanProductVariants(\n skus?: string[],\n options?: LeanProductVariantsOptions,\n): Promise<LeanProductVariant[]> {\n const queryGql = gql`#graphql\n query leanProductVariants($first: Int!, $after: String, $queryFilter: String) {\n productVariants(first: $first, after: $after, query: $queryFilter) {\n edges {\n node {\n id\n title\n sku\n product {\n id\n title\n status\n }\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n `\n\n const queryParts: string[] = []\n if (skus && skus.length > 0) {\n queryParts.push(skus.map((sku: string) => `sku:${sku}`).join(' OR '))\n }\n if (options?.activeOnly) {\n queryParts.push('product_status:active,draft')\n }\n\n const initialVariables: LeanProductVariantsQueryVariables = {\n first: 250,\n ...(queryParts.length > 0 && {\n queryFilter: queryParts.filter(Boolean).join(' AND '),\n }),\n }\n\n // Type for a single node from the productVariants query\n type SingleNode = NonNullable<\n NonNullable<\n LeanProductVariantsQuery['productVariants']\n >['edges'][number]['node']\n >\n\n const extractedNodes = await fetchShopifyGraphql<\n SingleNode,\n LeanProductVariantsQuery\n >({\n query: queryGql,\n variables: initialVariables,\n dataExtractor: (pageData: LeanProductVariantsQuery) => {\n if (!pageData.productVariants) {\n throw new Error(\n \"GraphQL response for product variants is missing the 'productVariants' field.\",\n )\n }\n const nodes: SingleNode[] = pageData.productVariants.edges.map(\n (edge: { node: SingleNode }) => edge.node,\n )\n return {\n nodes,\n pageInfo: pageData.productVariants.pageInfo,\n }\n },\n fetchAllPages: true,\n })\n\n const allVariants = extractedNodes.flatMap<LeanProductVariant>((v) => {\n if (v.sku) {\n return [\n {\n productId: v.product.id,\n productTitle: v.product.title,\n variantId: v.id,\n variantTitle: v.title,\n sku: v.sku,\n status: v.product.status,\n },\n ]\n }\n logger.debug(\n `Product ${v.product.title} (ID: ${v.product.id}) has a variant (ID: ${v.id}) with no SKU. Filtering out.`,\n )\n return []\n })\n\n return await returnOutputParsed(allVariants, GetLeanProductVariantsReturn)\n}\n","import z from 'zod'\nimport type {\n ProductVariantsBySkusQuery,\n ProductVariantsBySkusQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { gql, logger } from '../../utils/logger.js'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch.js'\nimport { returnOutputParsed } from '../../utils/zod.js'\n\nconst GetProductVariantsBySkusReturn = z.array(\n z.object({\n productId: z.string(),\n productTitle: z.string(),\n variantId: z.string(),\n variantTitle: z.string(),\n sku: z.string(),\n status: z.enum(['ACTIVE', 'ARCHIVED', 'DRAFT']),\n }),\n)\n\nexport type ProductVariantBySku = z.infer<\n typeof GetProductVariantsBySkusReturn\n>[number]\n\nexport type ProductVariantsBySkusOptions = {\n /** Filter to only active products (excludes ARCHIVED). Defaults to false. */\n activeOnly?: boolean\n}\n\n/**\n * Retrieves product variants from Shopify filtered by SKUs.\n * Variants missing a SKU will be filtered out and logged.\n *\n * @param {string[]} skus - Array of SKUs to filter by.\n * @param {ProductVariantsBySkusOptions} [options] - Optional settings.\n * @param {boolean} [options.activeOnly=false] - If true, excludes ARCHIVED products at query level.\n * @returns {Promise<ProductVariantBySku[]>} A promise that resolves to an array of product variant data.\n * @throws {Error} If the GraphQL query fails or returns no data.\n */\nexport async function getProductVariantsBySkus(\n skus: string[],\n options?: ProductVariantsBySkusOptions,\n): Promise<ProductVariantBySku[]> {\n if (skus.length === 0) {\n return []\n }\n\n const queryGql = gql`#graphql\n query productVariantsBySkus($first: Int!, $after: String, $queryFilter: String) {\n productVariants(first: $first, after: $after, query: $queryFilter) {\n edges {\n node {\n id\n title\n sku\n product {\n id\n title\n status\n }\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n `\n\n const skuFilter = skus.map((sku: string) => `sku:${sku}`).join(' OR ')\n const statusFilter = options?.activeOnly ? 'product_status:active,draft' : ''\n const queryFilter = [skuFilter, statusFilter].filter(Boolean).join(' AND ')\n\n const initialVariables: ProductVariantsBySkusQueryVariables = {\n first: 250,\n queryFilter,\n }\n\n type SingleNode = NonNullable<\n NonNullable<\n ProductVariantsBySkusQuery['productVariants']\n >['edges'][number]['node']\n >\n\n const extractedNodes = await fetchShopifyGraphql<\n SingleNode,\n ProductVariantsBySkusQuery\n >({\n query: queryGql,\n variables: initialVariables,\n dataExtractor: (pageData: ProductVariantsBySkusQuery) => {\n if (!pageData.productVariants) {\n throw new Error(\n \"GraphQL response for product variants is missing the 'productVariants' field.\",\n )\n }\n const nodes: SingleNode[] = pageData.productVariants.edges.map(\n (edge: { node: SingleNode }) => edge.node,\n )\n return {\n nodes,\n pageInfo: pageData.productVariants.pageInfo,\n }\n },\n fetchAllPages: true,\n })\n\n const allVariants = extractedNodes.flatMap<ProductVariantBySku>((v) => {\n if (!v.sku) {\n logger.debug(\n `Product ${v.product.title} (ID: ${v.product.id}) has a variant (ID: ${v.id}) with no SKU. Filtering out.`,\n )\n return []\n }\n return [\n {\n productId: v.product.id,\n productTitle: v.product.title,\n variantId: v.id,\n variantTitle: v.title,\n sku: v.sku,\n status: v.product.status,\n },\n ]\n })\n\n return await returnOutputParsed(allVariants, GetProductVariantsBySkusReturn)\n}\n","import z from 'zod'\nimport type {\n AllProductVariantsQuery,\n AllProductVariantsQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { logger } from '../../utils/logger.js'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch.js'\nimport { returnOutputParsed } from '../../utils/zod.js'\nimport { queryAllProductVariants } from './getAllProductVariants.queries.js'\n\nconst ProductVariantSchema = z.object({\n status: z.enum(['ACTIVE', 'ARCHIVED', 'DRAFT']),\n sku: z.string(),\n barcode: z.string().nullable(),\n price: z.string(),\n title: z.string(),\n url: z.string().nullable(),\n handle: z.string(),\n description: z.string(),\n imageUrl: z.string().nullable(),\n inventoryQuantity: z.number(),\n})\n\nconst GetAllProductVariantsReturn = z.array(ProductVariantSchema)\n\nexport type ProductVariant = z.infer<typeof ProductVariantSchema>\n\n/**\n * Retrieves all product variants from Shopify with full details.\n * Automatically handles pagination to fetch all variants.\n *\n * Each variant includes product info with combined title (product + variant title\n * when variant title is not \"Default Title\"), URL with variant ID, and inventory data.\n *\n * @returns {Promise<ProductVariant[]>} A promise that resolves to an array of product variants.\n * @throws {Error} If the GraphQL query fails or if the response is missing expected data.\n */\nexport async function getAllProductVariants(): Promise<ProductVariant[]> {\n const initialVariables: AllProductVariantsQueryVariables = { first: 250 }\n\n // Type for a single node from the productVariants query\n type SingleNode = NonNullable<\n NonNullable<\n AllProductVariantsQuery['productVariants']\n >['edges'][number]['node']\n >\n\n const extractedNodes = await fetchShopifyGraphql<\n SingleNode,\n AllProductVariantsQuery\n >({\n query: queryAllProductVariants,\n variables: initialVariables,\n dataExtractor: (pageData: AllProductVariantsQuery) => {\n if (!pageData.productVariants) {\n throw new Error(\n \"GraphQL response for product variants is missing the 'productVariants' field.\",\n )\n }\n const nodes: SingleNode[] = pageData.productVariants.edges.map(\n (edge: { node: SingleNode }) => edge.node,\n )\n return {\n nodes,\n pageInfo: pageData.productVariants.pageInfo,\n }\n },\n fetchAllPages: true,\n })\n\n logger.debug(`Fetched ${extractedNodes.length} product variants from Shopify`)\n\n const allVariants = extractedNodes.map<ProductVariant>((v) => {\n // Combine product title + variant title (unless \"Default Title\")\n const title =\n v.title === 'Default Title'\n ? v.product.title\n : `${v.product.title} ${v.title}`\n\n // Build URL with variant ID (using legacyResourceId)\n const url = v.product.onlineStoreUrl\n ? `${v.product.onlineStoreUrl}?variant=${v.legacyResourceId}`\n : null\n\n return {\n status: v.product.status,\n sku: v.sku ?? '',\n barcode: v.barcode ?? null,\n price: v.price,\n title,\n url,\n handle: v.product.handle,\n description: v.product.description,\n imageUrl: v.product.featuredImage?.url ?? null,\n inventoryQuantity: v.inventoryQuantity ?? 0,\n }\n })\n\n return await returnOutputParsed(allVariants, GetAllProductVariantsReturn)\n}\n","import { gql } from '../../utils/logger.js'\n\nexport const queryAllProductVariants = gql`#graphql\n query allProductVariants($first: Int!, $after: String) {\n productVariants(first: $first, after: $after) {\n edges {\n node {\n id\n legacyResourceId\n sku\n barcode\n inventoryQuantity\n price\n title\n product {\n status\n title\n description\n handle\n onlineStoreUrl\n featuredImage {\n url\n }\n }\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n`\n","import { gql } from '../../utils/logger.js'\n\nexport const queryOrderPaymentDetails = gql`#graphql\n query orderPaymentDetailsById($id: ID!) {\n order(id: $id) {\n transactions {\n amountSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n createdAt\n gateway\n formattedGateway\n kind\n paymentId\n }\n }\n }\n`\n","import type {\n OrderPaymentDetailsByIdQuery,\n OrderPaymentDetailsByIdQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { logger } from '../../utils/logger.js'\nimport {\n convertIdIntoGid,\n fetchShopifyGraphql,\n} from '../../utils/shopifyFetch.js'\nimport { queryOrderPaymentDetails } from './getOrderPaymentDetails.queries.js'\n\nexport type OrderPaymentDetails = NonNullable<\n OrderPaymentDetailsByIdQuery['order']\n>\n\n/**\n * Retrieves payment details for a single order from Shopify by its ID.\n * Returns undefined if no order is found with the specified ID.\n *\n * @param {bigint} id - The numerical Shopify order ID (e.g., 12345678n).\n * @returns {Promise<OrderPaymentDetails | undefined>} A promise that resolves to the order payment data or undefined if not found.\n * @throws {Error} If the GraphQL query fails.\n */\nexport async function getOrderPaymentDetailsById(\n id: bigint,\n): Promise<OrderPaymentDetails | undefined> {\n const variables: OrderPaymentDetailsByIdQueryVariables = {\n id: convertIdIntoGid(id, 'Order'),\n }\n\n const response = await fetchShopifyGraphql<OrderPaymentDetailsByIdQuery>({\n query: queryOrderPaymentDetails,\n variables,\n })\n\n if (!response.order) {\n logger.debug(`No order found with ID: ${id}`)\n return undefined\n }\n\n return response.order\n}\n","import { gql } from '../../utils/logger'\n\nexport const queryFulfillmentById = gql`#graphql\n query fulfillmentById($id: ID!) {\n fulfillment(id: $id) {\n id\n name\n createdAt\n updatedAt\n status\n totalQuantity\n estimatedDeliveryAt\n deliveredAt\n location {\n id\n legacyResourceId\n name\n }\n service {\n handle\n serviceName\n }\n trackingInfo(first: 10) {\n company\n number\n url\n }\n originAddress {\n address1\n address2\n city\n countryCode\n provinceCode\n zip\n }\n fulfillmentLineItems(first: 100) {\n edges {\n node {\n id\n quantity\n originalTotalSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n lineItem {\n id\n title\n sku\n variant {\n id\n }\n }\n }\n }\n }\n }\n }\n`\n","import type {\n FulfillmentByIdQuery,\n FulfillmentByIdQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { logger } from '../../utils/logger.js'\nimport {\n convertIdIntoGid,\n fetchShopifyGraphql,\n} from '../../utils/shopifyFetch.js'\nimport { queryFulfillmentById } from './getFulfillmentById.queries.js'\n\n// Fulfillment type - derived from the generated GraphQL types\nexport type Fulfillment = NonNullable<FulfillmentByIdQuery['fulfillment']>\n\n/**\n * Retrieves a single fulfillment from Shopify by its ID.\n * Returns undefined if no fulfillment is found with the specified ID.\n *\n * @param {string | number | bigint} id - The Shopify fulfillment ID. Can be a GID string (e.g., \"gid://shopify/Fulfillment/123456789\") or a numeric ID (e.g., 123456789 or 123456789n).\n * @returns {Promise<Fulfillment | undefined>} A promise that resolves to the fulfillment data or undefined if not found.\n * @throws {Error} If the GraphQL query fails or if the response structure is invalid.\n */\nexport async function getFulfillmentById(\n id: string | number | bigint,\n): Promise<Fulfillment | undefined> {\n const gid =\n typeof id === 'string'\n ? id\n : convertIdIntoGid(\n typeof id === 'number' ? BigInt(id) : id,\n 'Fulfillment',\n )\n\n const variables: FulfillmentByIdQueryVariables = { id: gid }\n\n const response = await fetchShopifyGraphql<FulfillmentByIdQuery>({\n query: queryFulfillmentById,\n variables,\n })\n\n if (!response.fulfillment) {\n logger.debug(`No fulfillment found with ID: ${id}`)\n return undefined\n }\n\n return response.fulfillment\n}\n","import { gql } from '../../utils/logger'\n\nexport const queryFulfillmentOrdersByOrderId = gql`#graphql\n query fulfillmentOrdersByOrderId($orderId: ID!) {\n order(id: $orderId) {\n fulfillmentOrders(first: 50) {\n edges {\n node {\n id\n status\n lineItems(first: 100) {\n edges {\n node {\n id\n remainingQuantity\n totalQuantity\n lineItem {\n id\n }\n }\n }\n }\n }\n }\n }\n }\n }\n`\n","import type {\n FulfillmentOrdersByOrderIdQuery,\n FulfillmentOrdersByOrderIdQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { logger } from '../../utils/logger.js'\nimport {\n convertIdIntoGid,\n fetchShopifyGraphql,\n} from '../../utils/shopifyFetch.js'\nimport { queryFulfillmentOrdersByOrderId } from './getFulfillmentOrdersByOrderId.queries.js'\n\n// FulfillmentOrder type - derived from the generated GraphQL types\ntype FulfillmentOrderEdge = NonNullable<\n FulfillmentOrdersByOrderIdQuery['order']\n>['fulfillmentOrders']['edges'][number]\n\nexport type FulfillmentOrder = FulfillmentOrderEdge['node']\n\n/**\n * Retrieves all fulfillment orders for a given Shopify order.\n * Returns an empty array if no order is found or if the order has no fulfillment orders.\n *\n * @param {string | number | bigint} orderId - The Shopify order ID. Can be a GID string (e.g., \"gid://shopify/Order/123456789\") or a numeric ID (e.g., 123456789 or 123456789n).\n * @returns {Promise<FulfillmentOrder[]>} A promise that resolves to an array of fulfillment orders.\n * @throws {Error} If the GraphQL query fails or if the response structure is invalid.\n */\nexport async function getFulfillmentOrdersByOrderId(\n orderId: string | number | bigint,\n): Promise<FulfillmentOrder[]> {\n const gid =\n typeof orderId === 'string'\n ? orderId\n : convertIdIntoGid(\n typeof orderId === 'number' ? BigInt(orderId) : orderId,\n 'Order',\n )\n\n const variables: FulfillmentOrdersByOrderIdQueryVariables = { orderId: gid }\n\n const response = await fetchShopifyGraphql<FulfillmentOrdersByOrderIdQuery>({\n query: queryFulfillmentOrdersByOrderId,\n variables,\n })\n\n if (!response.order) {\n logger.debug(`No order found with ID: ${orderId}`)\n return []\n }\n\n return response.order.fulfillmentOrders.edges.map((edge) => edge.node)\n}\n","import { gql } from '../../utils/logger'\n\nexport const queryCustomersByEmail = gql`#graphql\n query customersByEmail($query: String!, $first: Int!) {\n customers(first: $first, query: $query) {\n edges {\n node {\n id\n email\n firstName\n lastName\n numberOfOrders\n amountSpent {\n amount\n currencyCode\n }\n defaultAddress {\n id\n address1\n address2\n city\n province\n country\n zip\n phone\n }\n addresses {\n id\n address1\n address2\n city\n province\n country\n zip\n phone\n }\n }\n }\n }\n }\n`\n","import type {\n CustomersByEmailQuery,\n CustomersByEmailQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { logger } from '../../utils/logger.js'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch.js'\nimport { queryCustomersByEmail } from './getCustomersByEmail.queries.js'\n\n// Customer type - derived from the generated GraphQL types\nexport type Customer =\n CustomersByEmailQuery['customers']['edges'][number]['node']\n\n/**\n * Retrieves customers from Shopify by their email address.\n * Returns an empty array if no customers are found.\n *\n * @param {string} email - The email address to search for.\n * @param {number} limit - Maximum number of customers to return. Defaults to 10.\n * @returns {Promise<Customer[]>} A promise that resolves to an array of customers.\n * @throws {Error} If the GraphQL query fails or if the response structure is invalid.\n */\nexport async function getCustomersByEmail(\n email: string,\n limit = 10,\n): Promise<Customer[]> {\n const variables: CustomersByEmailQueryVariables = {\n query: `email:${email}`,\n first: limit,\n }\n\n const response = await fetchShopifyGraphql<CustomersByEmailQuery>({\n query: queryCustomersByEmail,\n variables,\n })\n\n const customers = response.customers.edges.map((edge) => edge.node)\n\n logger.debug(`Found ${customers.length} customers for email: ${email}`)\n\n return customers\n}\n","import { gql } from '../../utils/logger'\n\nexport const queryCustomerSegmentMembersWithStatistics = gql`#graphql\n query customerSegmentMembersWithStatistics($query: String!, $first: Int!, $statisticsAttributeName: String!) {\n customerSegmentMembers(query: $query, first: $first) {\n statistics {\n attributeStatistics(attributeName: $statisticsAttributeName) {\n sum\n average\n }\n }\n edges {\n node {\n id\n firstName\n lastName\n displayName\n defaultEmailAddress {\n emailAddress\n }\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n totalCount\n }\n }\n`\n","import type {\n CustomerSegmentMembersWithStatisticsQuery,\n CustomerSegmentMembersWithStatisticsQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { logger } from '../../utils/logger.js'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch.js'\nimport { queryCustomerSegmentMembersWithStatistics } from './getCustomerSegmentMembers.queries.js'\n\n// Segment member type - derived from the generated GraphQL types\nexport type CustomerSegmentMember =\n CustomerSegmentMembersWithStatisticsQuery['customerSegmentMembers']['edges'][number]['node']\n\n// Statistics type\nexport type SegmentAttributeStatistics =\n CustomerSegmentMembersWithStatisticsQuery['customerSegmentMembers']['statistics']['attributeStatistics']\n\nexport interface CustomerSegmentMembersResult {\n members: CustomerSegmentMember[]\n totalCount: number\n statistics: {\n attributeStatistics: SegmentAttributeStatistics\n }\n}\n\n/**\n * Retrieves customer segment members from Shopify based on a segment query.\n * Returns members with statistics for the specified attribute.\n *\n * @param {string} query - The segment query filter string (e.g., \"customer_account_status = 'ENABLED'\").\n * @param {string} statisticsAttributeName - Attribute name for statistics (e.g., \"amount_spent\").\n * @param {number} limit - Maximum number of members to return. Defaults to 250.\n * @returns {Promise<CustomerSegmentMembersResult>} Members with statistics.\n * @throws {Error} If the GraphQL query fails.\n */\nexport async function getCustomerSegmentMembers(\n query: string,\n statisticsAttributeName: string,\n limit = 250,\n): Promise<CustomerSegmentMembersResult> {\n const variables: CustomerSegmentMembersWithStatisticsQueryVariables = {\n query,\n first: limit,\n statisticsAttributeName,\n }\n\n const response =\n await fetchShopifyGraphql<CustomerSegmentMembersWithStatisticsQuery>({\n query: queryCustomerSegmentMembersWithStatistics,\n variables,\n })\n\n const members = response.customerSegmentMembers.edges.map((edge) => edge.node)\n\n logger.debug(`Found ${members.length} customer segment members`)\n\n return {\n members,\n totalCount: response.customerSegmentMembers.totalCount,\n statistics: response.customerSegmentMembers.statistics,\n }\n}\n","import { gql } from '../../utils/logger'\n\nexport const queryOrdersByCustomerId = gql`#graphql\n query ordersByCustomerId($customerId: ID!, $first: Int!) {\n customer(id: $customerId) {\n id\n orders(first: $first, reverse: true) {\n edges {\n node {\n id\n name\n createdAt\n cancelledAt\n cancelReason\n displayFulfillmentStatus\n totalPriceSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n lineItems(first: 100) {\n edges {\n node {\n sku\n title\n image {\n url\n width\n height\n altText\n }\n }\n }\n }\n }\n }\n }\n }\n }\n`\n","import type {\n OrdersByCustomerIdQuery,\n OrdersByCustomerIdQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { logger } from '../../utils/logger.js'\nimport {\n convertIdIntoGid,\n fetchShopifyGraphql,\n} from '../../utils/shopifyFetch.js'\nimport { queryOrdersByCustomerId } from './getOrdersByCustomerId.queries.js'\n\n// OrderPreview type - derived from the generated GraphQL types\ntype CustomerOrders = NonNullable<OrdersByCustomerIdQuery['customer']>['orders']\nexport type OrderPreview = CustomerOrders['edges'][number]['node']\n\n/**\n * Retrieves orders for a specific customer from Shopify.\n * Returns orders sorted by most recent first, or an empty array if customer not found.\n *\n * @param {number | bigint} customerId - The numerical Shopify customer ID.\n * @param {number} limit - Maximum number of orders to return. Defaults to 250.\n * @returns {Promise<OrderPreview[]>} A promise that resolves to an array of order previews.\n * @throws {Error} If the GraphQL query fails.\n */\nexport async function getOrdersByCustomerId(\n customerId: number | bigint,\n limit = 250,\n): Promise<OrderPreview[]> {\n const bigIntId =\n typeof customerId === 'number' ? BigInt(customerId) : customerId\n const gid = convertIdIntoGid(bigIntId, 'Customer')\n\n const variables: OrdersByCustomerIdQueryVariables = {\n customerId: gid,\n first: limit,\n }\n\n const response = await fetchShopifyGraphql<OrdersByCustomerIdQuery>({\n query: queryOrdersByCustomerId,\n variables,\n })\n\n if (!response.customer) {\n logger.debug(`No customer found with ID: ${customerId}`)\n return []\n }\n\n const orders = response.customer.orders.edges.map((edge) => edge.node)\n\n logger.debug(`Got ${orders.length} orders for customer ${customerId}`)\n\n return orders\n}\n","/**\n * Extract numeric ID from a Shopify GID string.\n *\n * @example\n * parseGid('gid://shopify/Order/12345678901234') // → 12345678901234\n * parseGid('gid://shopify/LineItem/999') // → 999\n */\nexport function parseGid(gid: string): number {\n const match = gid.match(/\\d+$/)\n return match ? Number.parseInt(match[0], 10) : 0\n}\n","import { gql } from '../../utils/logger'\n\nexport const queryMetaobjectByHandle = gql`#graphql\n query metaobjectByHandle($handle: MetaobjectHandleInput!) {\n metaobjectByHandle(handle: $handle) {\n id\n handle\n type\n displayName\n updatedAt\n fields {\n key\n value\n type\n }\n }\n }\n`\n","import type {\n MetaobjectByHandleQuery,\n MetaobjectByHandleQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport type { MetaobjectHandleInput } from '../../generated-api-types/2025-04/admin.types.js'\nimport { logger } from '../../utils/logger.js'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch.js'\nimport { queryMetaobjectByHandle } from './getMetaobjectByHandle.queries.js'\n\n// Metaobject type - derived from the generated GraphQL types\nexport type Metaobject = NonNullable<\n MetaobjectByHandleQuery['metaobjectByHandle']\n>\n\n/**\n * Retrieves a metaobject from Shopify by its handle.\n * Returns undefined if no metaobject is found with the specified type and handle.\n *\n * @param handle - The handle input containing type and handle\n * @returns A promise that resolves to the metaobject data or undefined if not found.\n */\nexport async function getMetaobjectByHandle(\n handle: MetaobjectHandleInput,\n): Promise<Metaobject | undefined> {\n const variables: MetaobjectByHandleQueryVariables = { handle }\n\n const response = await fetchShopifyGraphql<MetaobjectByHandleQuery>({\n query: queryMetaobjectByHandle,\n variables,\n })\n\n if (!response.metaobjectByHandle) {\n logger.debug(\n `No metaobject found with type \"${handle.type}\" and handle \"${handle.handle}\"`,\n )\n return undefined\n }\n\n return response.metaobjectByHandle\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAM,EAAE,IAAI,IAAI;AAET,IAAM,MAAM,OAAO;AAE1B,IAAM,YAAY;AAAA,EAChB,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AACT;AAIA,SAAS,YACP,SACA,aACc;AACd,MAAI,eAAe,eAAe,WAAW;AAC3C,WAAO;AAAA,EACT;AAEA,MAAI,YAAY,QAAQ;AACtB,WAAO;AAAA,EACT;AAEA,MAAI,YAAY,cAAc;AAC5B,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEO,IAAM,qBAAqB,YAAY,IAAI,UAAU,IAAI,SAAS;AACzE,IAAM,sBAAsB,UAAU,kBAAkB;AAEjD,IAAM,SAAS;AAAA,EACpB,OAAO,IAAI,SAAoB;AAC7B,QAAI,UAAU,SAAS,qBAAqB;AAE1C,cAAQ,MAAM,GAAG,IAAI;AAAA,IACvB;AAAA,EACF;AAAA,EACA,MAAM,IAAI,SAAoB;AAC5B,QAAI,UAAU,QAAQ,qBAAqB;AAEzC,c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T;AAEA,SAAO,SAAS;AAClB;","names":["import_shopify_api","dotenv","env","mutation","mutation","mutation","mutation","mutation","mutation","mutation","toGid","mutation","mutation","import_zod","import_zod","z","z","import_zod","z","import_zod","z","import_zod","z","import_zod","z"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/utils/logger.ts","../src/utils/shopifyClient.ts","../src/utils/apiVersion.ts","../src/utils/shopifyFetch.ts","../src/mutations/customers/deleteCustomerById.ts","../src/mutations/files/deleteFilesByIds.ts","../src/mutations/files/createFile.ts","../src/mutations/metaobjectDefinitions/createMetaobjectDefinition.ts","../src/mutations/fulfillments/createFulfillment.ts","../src/queries/fulfillments/getFulfillmentTrackingIds.queries.ts","../src/queries/fulfillments/getFulfillmentTrackingIds.ts","../src/mutations/fulfillments/updateFulfillmentTracking.ts","../src/mutations/orders/cancelOrderById.ts","../src/mutations/refunds/createRefund.ts","../src/mutations/productVariantsBulkUpdate/bulkUpdateProductVariants.ts","../src/mutations/metaobjects/upsertMetaobject.ts","../src/queries/orders/calculateRefund.queries.ts","../src/queries/orders/calculateRefund.ts","../src/queries/orders/getOrderById.ts","../src/utils/zod.ts","../src/queries/orders/getOrderById.queries.ts","../src/queries/orders/getOrderByName.ts","../src/queries/orders/getOrderByName.queries.ts","../src/queries/orders/getOrderCancellationInfo.queries.ts","../src/queries/orders/getOrderCancellationInfo.ts","../src/queries/productVariants/getLeanProductVariants.ts","../src/queries/productVariants/getProductVariantsBySkus.ts","../src/queries/productVariants/getAllProductVariants.ts","../src/queries/productVariants/getAllProductVariants.queries.ts","../src/queries/orders/getOrderPaymentDetails.queries.ts","../src/queries/orders/getOrderPaymentDetails.ts","../src/queries/fulfillments/getFulfillmentById.queries.ts","../src/queries/fulfillments/getFulfillmentById.ts","../src/queries/fulfillmentOrders/getFulfillmentOrdersByOrderId.queries.ts","../src/queries/fulfillmentOrders/getFulfillmentOrdersByOrderId.ts","../src/queries/customers/getCustomersByEmail.queries.ts","../src/queries/customers/getCustomersByEmail.ts","../src/queries/customerSegments/getCustomerSegmentMembers.queries.ts","../src/queries/customerSegments/getCustomerSegmentMembers.ts","../src/queries/orders/getOrdersByCustomerId.queries.ts","../src/queries/orders/getOrdersByCustomerId.ts","../src/utils/parseGid.ts","../src/queries/metaobjects/getMetaobjectByHandle.queries.ts","../src/queries/metaobjects/getMetaobjectByHandle.ts"],"sourcesContent":["export { deleteCustomerById } from './mutations/customers/deleteCustomerById.js'\nexport { deleteFilesByIds } from './mutations/files/deleteFilesByIds.js'\nexport { createFile } from './mutations/files/createFile.js'\nexport {\n createMetaobjectDefinition,\n type CreateMetaobjectDefinitionInput,\n type CreateMetaobjectDefinitionResult,\n type MetaobjectFieldDefinition,\n} from './mutations/metaobjectDefinitions/createMetaobjectDefinition.js'\nexport {\n createFulfillment,\n type CreateFulfillmentResult,\n type FulfillmentLineItem,\n} from './mutations/fulfillments/createFulfillment.js'\nexport {\n updateFulfillmentTracking,\n type UpdateFulfillmentTrackingResult,\n} from './mutations/fulfillments/updateFulfillmentTracking.js'\nexport { cancelOrderById } from './mutations/orders/cancelOrderById.js'\nexport {\n createRefund,\n type CreateRefundOptions,\n type CreateRefundResult,\n type CreateRefundLineItem,\n type CreateRefundTransaction,\n type RefundMoney,\n} from './mutations/refunds/createRefund.js'\nexport {\n bulkUpdateProductVariants,\n type BulkUpdateProductVariantsResult,\n type VariantUpdateInput,\n} from './mutations/productVariantsBulkUpdate/bulkUpdateProductVariants.js'\nexport {\n upsertMetaobject,\n type UpsertMetaobjectInput,\n type UpsertMetaobjectResult,\n} from './mutations/metaobjects/upsertMetaobject.js'\nexport {\n calculateRefund,\n type CalculateRefundOptions,\n type CalculateRefundLineItem,\n type SuggestedRefund,\n} from './queries/orders/calculateRefund.js'\nexport {\n ShopifyUserError,\n type ShopifyUserErrorDetail,\n} from './utils/shopifyFetch.js'\nexport {\n getOrderById,\n type FullOrder,\n type LeanOrder,\n} from './queries/orders/getOrderById.js'\nexport {\n getOrderByName,\n type FullOrderByName,\n type LeanOrderByName,\n} from './queries/orders/getOrderByName.js'\nexport {\n getOrderCancellationInfoByName,\n type OrderCancellationInfo,\n} from './queries/orders/getOrderCancellationInfo.js'\nexport {\n getLeanProductVariants,\n type LeanProductVariant,\n type LeanProductVariantsOptions,\n} from './queries/productVariants/getLeanProductVariants.js'\nexport {\n getProductVariantsBySkus,\n type ProductVariantBySku,\n type ProductVariantsBySkusOptions,\n} from './queries/productVariants/getProductVariantsBySkus.js'\nexport {\n getAllProductVariants,\n type ProductVariant,\n} from './queries/productVariants/getAllProductVariants.js'\nexport {\n getOrderPaymentDetailsById,\n type OrderPaymentDetails,\n} from './queries/orders/getOrderPaymentDetails.js'\nexport {\n getFulfillmentById,\n type Fulfillment,\n} from './queries/fulfillments/getFulfillmentById.js'\nexport {\n getFulfillmentOrdersByOrderId,\n type FulfillmentOrder,\n} from './queries/fulfillmentOrders/getFulfillmentOrdersByOrderId.js'\nexport {\n getFulfillmentTrackingIds,\n type FulfillmentTrackingIds,\n} from './queries/fulfillments/getFulfillmentTrackingIds.js'\nexport {\n getCustomersByEmail,\n type Customer,\n} from './queries/customers/getCustomersByEmail.js'\nexport {\n getCustomerSegmentMembers,\n type CustomerSegmentMember,\n type CustomerSegmentMembersResult,\n type SegmentAttributeStatistics,\n} from './queries/customerSegments/getCustomerSegmentMembers.js'\nexport {\n getOrdersByCustomerId,\n type OrderPreview,\n} from './queries/orders/getOrdersByCustomerId.js'\nexport { parseGid } from './utils/parseGid.js'\nexport {\n getMetaobjectByHandle,\n type Metaobject,\n} from './queries/metaobjects/getMetaobjectByHandle.js'\nexport type { MetaobjectHandleInput } from './generated-api-types/2025-04/admin.types.js'\n","const { env } = process\n\nexport const gql = String.raw\n\nconst logLevels = {\n silent: 0,\n error: 1,\n warn: 2,\n info: 3,\n debug: 4,\n} as const\n\ntype LogLevelName = keyof typeof logLevels\n\nfunction getLogLevel(\n nodeEnv: string | undefined,\n logLevelEnv: string | undefined,\n): LogLevelName {\n if (logLevelEnv && logLevelEnv in logLevels) {\n return logLevelEnv as LogLevelName\n }\n\n if (nodeEnv === 'test') {\n return 'silent'\n }\n\n if (nodeEnv === 'production') {\n return 'info'\n }\n return 'debug'\n}\n\nexport const activeLogLevelName = getLogLevel(env.NODE_ENV, env.LOG_LEVEL)\nconst activeLogLevelValue = logLevels[activeLogLevelName]\n\nexport const logger = {\n debug: (...args: unknown[]) => {\n if (logLevels.debug <= activeLogLevelValue) {\n // biome-ignore lint/suspicious/noConsole: <explanation>\n console.debug(...args)\n }\n },\n info: (...args: unknown[]) => {\n if (logLevels.info <= activeLogLevelValue) {\n // biome-ignore lint/suspicious/noConsole: <explanation>\n console.info(...args)\n }\n },\n warn: (...args: unknown[]) => {\n if (logLevels.warn <= activeLogLevelValue) {\n // biome-ignore lint/suspicious/noConsole: <explanation>\n console.warn(...args)\n }\n },\n error: (...args: unknown[]) => {\n if (logLevels.error <= activeLogLevelValue) {\n // biome-ignore lint/suspicious/noConsole: <explanation>\n console.error(...args)\n }\n },\n}\n","import {\n type GraphqlClient,\n LogSeverity,\n Session,\n shopifyApi,\n} from '@shopify/shopify-api'\nimport '@shopify/shopify-api/adapters/node'\nimport dotenv from 'dotenv'\nimport { z } from 'zod'\nimport { SHOPIFY_API_VERSION } from './apiVersion.js'\nimport { activeLogLevelName, logger } from './logger.js'\n\nexport { SHOPIFY_API_VERSION }\n\ndotenv.config()\n\nconst envSchema = z.object({\n SHOPIFY_API_KEY: z.string({\n required_error: 'SHOPIFY_API_KEY is required',\n }),\n SHOPIFY_API_SECRET: z.string({\n required_error: 'SHOPIFY_API_SECRET is required',\n }),\n SHOPIFY_API_HOSTNAME: z.string({\n required_error: 'SHOPIFY_API_HOSTNAME is required',\n }),\n SHOPIFY_ACCESS_TOKEN: z.string({\n required_error: 'SHOPIFY_ACCESS_TOKEN is required',\n }),\n NODE_ENV: z\n .enum(['development', 'production', 'test'])\n .default('development'),\n})\n\nconst mapLogLevelToShopifySeverity = (level: string): LogSeverity => {\n switch (level) {\n case 'silent':\n return LogSeverity.Error\n case 'debug':\n return LogSeverity.Debug\n case 'info':\n return LogSeverity.Info\n case 'warn':\n return LogSeverity.Warning\n case 'error':\n return LogSeverity.Error\n default:\n return LogSeverity.Info\n }\n}\n\nlet shopifyGraphqlClient: GraphqlClient\n\ntry {\n // biome-ignore lint/nursery/noProcessEnv: <explanation>\n const env = envSchema.parse(process.env)\n\n const shopify = shopifyApi({\n apiKey: env.SHOPIFY_API_KEY,\n apiSecretKey: env.SHOPIFY_API_SECRET,\n hostName: env.SHOPIFY_API_HOSTNAME,\n apiVersion: SHOPIFY_API_VERSION,\n isEmbeddedApp: false,\n logger: { level: mapLogLevelToShopifySeverity(activeLogLevelName) },\n future: {\n customerAddressDefaultFix: true,\n lineItemBilling: true,\n unstable_managedPricingSupport: false,\n },\n })\n\n const shopifySession = new Session({\n id: `custom-session-${env.SHOPIFY_API_HOSTNAME}`,\n shop: env.SHOPIFY_API_HOSTNAME,\n state: 'authenticated',\n isOnline: true,\n accessToken: env.SHOPIFY_ACCESS_TOKEN,\n })\n\n shopifyGraphqlClient = new shopify.clients.Graphql({\n session: shopifySession,\n })\n\n logger.info('Shopify API client initialized successfully.')\n} catch (error) {\n if (error instanceof z.ZodError) {\n const msg = JSON.stringify(error.format(), null, 2)\n logger.error(msg)\n } else {\n logger.error('Failed to initialize Shopify API client:', error)\n }\n throw error\n}\n\nexport { shopifyGraphqlClient as shopifyClient }\n","import { ApiVersion } from '@shopify/shopify-api'\n\n// https://shopify.dev/docs/api/admin-graphql/2025-04/\nexport const SHOPIFY_API_VERSION = ApiVersion.April25\n","import { logger } from './logger.js'\nimport { shopifyClient } from './shopifyClient.js'\n\nexport function convertIdIntoGid(\n id: bigint,\n type: 'Order' | 'Customer' | 'Fulfillment',\n): string {\n return `gid://shopify/${type}/${id}`\n}\n\ninterface PageInfo {\n hasNextPage: boolean\n endCursor?: string | null | undefined\n}\n\ninterface ShopifyErrorWithMessage {\n message?: string\n [key: string]: unknown\n}\n\nexport interface ShopifyUserErrorDetail {\n code?: string | null\n field?: string[] | null\n message?: string | null\n}\n\n/**\n * Custom error class for Shopify mutation userErrors.\n * Preserves the full error array so callers can inspect specific error codes.\n *\n * @example\n * try {\n * await cancelOrderById(orderId)\n * } catch (error) {\n * if (error instanceof ShopifyUserError) {\n * const alreadyCancelled = error.errors.some(e => e.code === 'ORDER_ALREADY_CANCELLED')\n * if (alreadyCancelled) { ... }\n * }\n * }\n */\nexport class ShopifyUserError extends Error {\n readonly errors: ShopifyUserErrorDetail[]\n\n constructor(message: string, errors: ShopifyUserErrorDetail[]) {\n super(message)\n this.name = 'ShopifyUserError'\n this.errors = errors\n }\n}\n\ntype TExtractorFunctionType<TResultNode, TPageData> = (pageData: TPageData) => {\n nodes: TResultNode[]\n pageInfo?: PageInfo\n userErrors?: ShopifyUserErrorDetail[]\n}\n\nexport async function fetchShopifyGraphql<TResultNode, TPageData>(params: {\n query: string\n variables: Record<string, unknown>\n dataExtractor?: TExtractorFunctionType<TResultNode, TPageData>\n fetchAllPages?: boolean\n}): Promise<TResultNode[]>\nexport async function fetchShopifyGraphql<TReturnType>(params: {\n query: string\n variables: Record<string, unknown>\n}): Promise<TReturnType>\nexport async function fetchShopifyGraphql<\n TResultNode,\n TPageData,\n TReturnType,\n>(params: {\n query: string\n variables: Record<string, unknown>\n dataExtractor?: TExtractorFunctionType<TResultNode, TPageData>\n fetchAllPages?: boolean\n}): Promise<TResultNode[] | TReturnType> {\n const {\n query,\n variables: initialVariables,\n dataExtractor,\n fetchAllPages = false,\n } = params\n\n let currentVariables = { ...initialVariables }\n\n if (!dataExtractor) {\n return makeRequest<NonNullable<TReturnType>>(query, currentVariables)\n }\n\n const allNodes: TResultNode[] = []\n let hasNextLoop = true\n\n do {\n const response = await makeRequest<TPageData>(query, currentVariables)\n const { nodes, pageInfo, userErrors } = dataExtractor(response)\n\n // Handle Shopify mutation userErrors pattern\n if (Array.isArray(userErrors) && userErrors.length > 0) {\n const errorMessages = userErrors\n .map((e) => e.message || JSON.stringify(e))\n .join('\\n')\n logger.error('Shopify mutation userErrors:', errorMessages)\n throw new ShopifyUserError(\n `Shopify mutation userErrors: ${errorMessages}`,\n userErrors,\n )\n }\n\n allNodes.push(...nodes)\n\n hasNextLoop = fetchAllPages ? !!pageInfo?.hasNextPage : false\n if (hasNextLoop && pageInfo?.endCursor) {\n currentVariables = {\n ...currentVariables,\n after: pageInfo.endCursor,\n }\n }\n } while (hasNextLoop)\n\n return allNodes\n}\n\nasync function makeRequest<TReturnDataType>(\n query: string,\n variables: Record<string, unknown>,\n): Promise<NonNullable<TReturnDataType>> {\n type ShopifyRequestErrorType = {\n errors?: ShopifyErrorWithMessage | ShopifyErrorWithMessage[]\n }\n\n const response = (await shopifyClient.request<TReturnDataType>(query, {\n variables,\n })) as { data?: TReturnDataType } & ShopifyRequestErrorType\n\n if (response.errors) {\n let errorMessages = 'GraphQL query failed.'\n const errors = response.errors\n if (Array.isArray(errors)) {\n errorMessages = errors\n .map((e: ShopifyErrorWithMessage) => e.message || JSON.stringify(e))\n .join('\\n')\n } else if (\n typeof errors === 'object' &&\n errors !== null &&\n 'message' in errors\n ) {\n errorMessages = errors.message || JSON.stringify(errors)\n } else if (typeof errors === 'string') {\n errorMessages = errors\n } else {\n errorMessages = JSON.stringify(errors)\n }\n logger.error('GraphQL query failed:', errorMessages)\n throw new Error(`GraphQL errors: ${errorMessages}`)\n }\n\n if (!response.data) {\n throw new Error('No data in Shopify API response')\n }\n\n return response.data\n}\n","import type {\n CustomerDeleteMutation,\n CustomerDeleteMutationVariables,\n} from '../../generated-api-types/2025-04/admin.generated'\nimport { gql } from '../../utils/logger'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch'\n\ntype SingleNode = { deletedCustomerId: string | null }\n\n/**\n * Deletes a customer from Shopify by their ID.\n * @param customerId - The customer ID (GID string, e.g., \"gid://shopify/Customer/123\")\n * @returns The deleted customer ID, or null if not found\n * @throws ShopifyUserError if Shopify returns user errors\n */\nexport async function deleteCustomerById(\n customerId: string,\n): Promise<string | undefined> {\n const mutation = gql`#graphql\n mutation customerDelete($input: CustomerDeleteInput!) {\n customerDelete(input: $input) {\n deletedCustomerId\n userErrors {\n field\n message\n }\n }\n }\n `\n\n const variables: CustomerDeleteMutationVariables = {\n input: { id: customerId },\n }\n\n const response = await fetchShopifyGraphql<\n SingleNode,\n CustomerDeleteMutation\n >({\n query: mutation,\n variables,\n dataExtractor: (data: CustomerDeleteMutation) => {\n if (!data.customerDelete) {\n throw new Error(\"GraphQL response missing 'customerDelete' field\")\n }\n return {\n nodes: [\n { deletedCustomerId: data.customerDelete.deletedCustomerId ?? null },\n ],\n userErrors: data.customerDelete.userErrors,\n }\n },\n })\n\n return response[0]?.deletedCustomerId ?? undefined\n}\n","import type {\n FileDeleteMutation,\n FileDeleteMutationVariables,\n} from '../../generated-api-types/2025-04/admin.generated'\nimport { gql } from '../../utils/logger'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch'\n\ntype SingleNode = { deletedFileIds: string[] }\n\n/**\n * Deletes files from Shopify by their IDs.\n * @param fileIds - Array of file IDs to delete (e.g., \"gid://shopify/MediaImage/123\")\n * @returns Array of successfully deleted file IDs\n * @throws ShopifyUserError if Shopify returns user errors\n */\nexport async function deleteFilesByIds(fileIds: string[]): Promise<string[]> {\n if (fileIds.length === 0) {\n return []\n }\n\n const mutation = gql`#graphql\n mutation fileDelete($fileIds: [ID!]!) {\n fileDelete(fileIds: $fileIds) {\n deletedFileIds\n userErrors {\n code\n field\n message\n }\n }\n }\n `\n\n const variables: FileDeleteMutationVariables = { fileIds }\n\n const response = await fetchShopifyGraphql<SingleNode, FileDeleteMutation>({\n query: mutation,\n variables,\n dataExtractor: (data: FileDeleteMutation) => {\n if (!data.fileDelete) {\n throw new Error(\"GraphQL response missing 'fileDelete' field\")\n }\n return {\n nodes: [{ deletedFileIds: data.fileDelete.deletedFileIds ?? [] }],\n userErrors: data.fileDelete.userErrors,\n }\n },\n })\n\n return response[0]?.deletedFileIds ?? []\n}\n","import type {\n CreateFileMutation,\n CreateFileMutationVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { gql, logger } from '../../utils/logger.js'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch.js'\n\nconst mutation = gql`#graphql\n mutation createFile($files: [FileCreateInput!]!) {\n fileCreate(files: $files) {\n files {\n id\n }\n userErrors {\n code\n field\n message\n }\n }\n }\n`\n\n/**\n * Creates a file in Shopify from an external URL.\n *\n * @param url - The HTTPS URL of the file to upload (must be publicly accessible)\n * @param altText - Alt text description for accessibility\n * @param filename - The filename to use in Shopify\n * @returns Promise resolving to the created file ID\n * @throws {Error} When the URL doesn't start with https://\n * @throws {ShopifyUserError} When the mutation fails\n *\n * @example\n * const fileId = await createFile(\n * 'https://example.com/image.png',\n * 'Product image',\n * 'product-image.png'\n * )\n */\nexport async function createFile(\n url: string,\n altText: string,\n filename: string,\n): Promise<string> {\n if (!url.startsWith('https://')) {\n throw new Error(\n `Not a valid public URL (https://) provided for file (url: ${url}).`,\n )\n }\n\n logger.debug(`Creating file: ${filename}`)\n\n const variables: CreateFileMutationVariables = {\n files: [\n {\n originalSource: url,\n alt: altText,\n filename: filename,\n },\n ],\n }\n\n const result = await fetchShopifyGraphql<{ id: string }, CreateFileMutation>({\n query: mutation,\n variables,\n dataExtractor: (data) => {\n if (!data.fileCreate) {\n throw new Error(\"GraphQL response missing 'fileCreate' field\")\n }\n\n const file = data.fileCreate.files?.[0]\n return {\n nodes: file ? [{ id: file.id }] : [],\n userErrors: data.fileCreate.userErrors,\n }\n },\n })\n\n const fileId = result[0]?.id\n if (!fileId) {\n throw new Error('File creation returned no result')\n }\n\n logger.debug(`Successfully created file ${fileId}`)\n\n return fileId\n}\n","import type {\n CreateMetaobjectDefinitionMutation,\n CreateMetaobjectDefinitionMutationVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { gql, logger } from '../../utils/logger.js'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch.js'\n\nexport type MetaobjectFieldDefinition = {\n key: string\n name?: string\n type: string\n description?: string\n required?: boolean\n validations?: Array<{ name: string; value: string }>\n}\n\nexport type CreateMetaobjectDefinitionInput = {\n type: string\n name?: string\n description?: string\n displayNameKey?: string\n fieldDefinitions: MetaobjectFieldDefinition[]\n}\n\nexport type CreateMetaobjectDefinitionResult = {\n id: string\n name: string\n type: string\n}\n\nconst mutation = gql`#graphql\n mutation createMetaobjectDefinition($definition: MetaobjectDefinitionCreateInput!) {\n metaobjectDefinitionCreate(definition: $definition) {\n metaobjectDefinition {\n id\n name\n type\n }\n userErrors {\n code\n field\n message\n }\n }\n }\n`\n\n/**\n * Creates a metaobject definition in Shopify.\n *\n * @param input - The metaobject definition input\n * @returns Promise resolving to the created metaobject definition\n * @throws {ShopifyUserError} When the mutation fails\n * @throws {Error} When GraphQL errors occur\n *\n * @example\n * await createMetaobjectDefinition({\n * type: 'my_custom_type',\n * name: 'My Custom Type',\n * description: 'A custom metaobject definition',\n * fieldDefinitions: [\n * { key: 'title', name: 'Title', type: 'single_line_text_field' },\n * { key: 'description', name: 'Description', type: 'multi_line_text_field' },\n * ],\n * })\n */\nexport async function createMetaobjectDefinition(\n input: CreateMetaobjectDefinitionInput,\n): Promise<CreateMetaobjectDefinitionResult> {\n logger.debug(`Creating metaobject definition with type: ${input.type}`)\n\n const variables: CreateMetaobjectDefinitionMutationVariables = {\n definition: {\n type: input.type,\n name: input.name,\n description: input.description,\n displayNameKey: input.displayNameKey,\n fieldDefinitions: input.fieldDefinitions,\n },\n }\n\n const result = await fetchShopifyGraphql<\n CreateMetaobjectDefinitionResult,\n CreateMetaobjectDefinitionMutation\n >({\n query: mutation,\n variables,\n dataExtractor: (data) => {\n if (!data.metaobjectDefinitionCreate) {\n throw new Error(\n \"GraphQL response missing 'metaobjectDefinitionCreate' field\",\n )\n }\n\n const metaobjectDefinition =\n data.metaobjectDefinitionCreate.metaobjectDefinition\n\n if (!metaobjectDefinition) {\n return {\n nodes: [],\n userErrors: data.metaobjectDefinitionCreate.userErrors,\n }\n }\n\n return {\n nodes: [\n {\n id: metaobjectDefinition.id,\n name: metaobjectDefinition.name,\n type: metaobjectDefinition.type,\n },\n ],\n userErrors: data.metaobjectDefinitionCreate.userErrors,\n }\n },\n })\n\n const definitionResult = result[0]\n if (!definitionResult) {\n throw new Error('Metaobject definition creation returned no result')\n }\n\n logger.debug(\n `Successfully created metaobject definition ${definitionResult.id}`,\n )\n\n return definitionResult\n}\n","import type {\n CreateFulfillmentMutation,\n CreateFulfillmentMutationVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { gql, logger } from '../../utils/logger.js'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch.js'\n\nexport type FulfillmentLineItem = {\n id: number | bigint | string\n quantity: number\n}\n\nexport type CreateFulfillmentResult = {\n id: string\n status: string\n trackingInfo: {\n company: string | null\n number: string | null\n }[]\n}\n\nconst mutation = gql`#graphql\n mutation createFulfillment($fulfillment: FulfillmentInput!) {\n fulfillmentCreate(fulfillment: $fulfillment) {\n fulfillment {\n id\n status\n trackingInfo {\n company\n number\n }\n }\n userErrors {\n field\n message\n }\n }\n }\n`\n\nfunction toGid(id: number | bigint | string, type: string): string {\n if (typeof id === 'string' && id.startsWith('gid://')) {\n return id\n }\n return `gid://shopify/${type}/${id}`\n}\n\n/**\n * Creates a fulfillment for a fulfillment order with optional tracking info.\n *\n * @param fulfillmentOrderId - The fulfillment order ID (numeric, bigint, or GID string)\n * @param fulfillmentOrderLineItems - Line items to fulfill with their quantities\n * @param options - Optional tracking and notification settings\n * @returns Promise resolving to the created fulfillment\n * @throws {ShopifyUserError} When the mutation fails\n * @throws {Error} When GraphQL errors occur\n *\n * @example\n * // Fulfill specific line items without tracking\n * await createFulfillment(123456789, [{ id: 111, quantity: 2 }])\n *\n * // Fulfill all items without tracking\n * await createFulfillment(123456789, [])\n *\n * // Fulfill with tracking info\n * await createFulfillment(\n * 123456789,\n * [{ id: 111, quantity: 2 }],\n * { trackingNumber: 'TRACK123', carrier: 'DHL', notifyCustomer: true }\n * )\n */\nexport async function createFulfillment(\n fulfillmentOrderId: number | bigint | string,\n fulfillmentOrderLineItems: FulfillmentLineItem[],\n options: {\n trackingNumber?: string\n carrier?: string\n trackingUrl?: string\n notifyCustomer?: boolean\n } = {},\n): Promise<CreateFulfillmentResult> {\n const {\n trackingNumber,\n carrier,\n trackingUrl,\n notifyCustomer = true,\n } = options\n\n const fulfillmentOrderGid = toGid(fulfillmentOrderId, 'FulfillmentOrder')\n\n logger.debug(`Creating fulfillment for order ${fulfillmentOrderGid}`)\n\n const lineItems = fulfillmentOrderLineItems.map((item) => ({\n id: toGid(item.id, 'FulfillmentOrderLineItem'),\n quantity: item.quantity,\n }))\n\n const variables: CreateFulfillmentMutationVariables = {\n fulfillment: {\n lineItemsByFulfillmentOrder: [\n {\n fulfillmentOrderId: fulfillmentOrderGid,\n ...(lineItems.length > 0\n ? { fulfillmentOrderLineItems: lineItems }\n : {}),\n },\n ],\n notifyCustomer,\n ...(trackingNumber\n ? {\n trackingInfo: {\n number: trackingNumber,\n ...(carrier ? { company: carrier } : {}),\n ...(trackingUrl ? { url: trackingUrl } : {}),\n },\n }\n : {}),\n },\n }\n\n const result = await fetchShopifyGraphql<\n CreateFulfillmentResult,\n CreateFulfillmentMutation\n >({\n query: mutation,\n variables,\n dataExtractor: (data) => {\n if (!data.fulfillmentCreate) {\n throw new Error(\"GraphQL response missing 'fulfillmentCreate' field\")\n }\n\n const fulfillment = data.fulfillmentCreate.fulfillment\n if (!fulfillment) {\n return {\n nodes: [],\n userErrors: data.fulfillmentCreate.userErrors,\n }\n }\n\n return {\n nodes: [\n {\n id: fulfillment.id,\n status: fulfillment.status,\n trackingInfo: fulfillment.trackingInfo.map((info) => ({\n company: info.company ?? null,\n number: info.number ?? null,\n })),\n },\n ],\n userErrors: data.fulfillmentCreate.userErrors,\n }\n },\n })\n\n const fulfillmentResult = result[0]\n if (!fulfillmentResult) {\n throw new Error('Fulfillment creation returned no result')\n }\n\n logger.debug(`Successfully created fulfillment ${fulfillmentResult.id}`)\n\n return fulfillmentResult\n}\n","import { gql } from '../../utils/logger'\n\nexport const queryFulfillmentTrackingIds = gql`#graphql\n query fulfillmentTrackingIds($id: ID!) {\n fulfillment(id: $id) {\n id\n trackingInfo(first: 50) {\n company\n number\n }\n }\n }\n`\n","import type {\n FulfillmentTrackingIdsQuery,\n FulfillmentTrackingIdsQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { logger } from '../../utils/logger.js'\nimport {\n convertIdIntoGid,\n fetchShopifyGraphql,\n} from '../../utils/shopifyFetch.js'\nimport { queryFulfillmentTrackingIds } from './getFulfillmentTrackingIds.queries.js'\n\nexport type FulfillmentTrackingIds = {\n trackingNumbers: string[]\n trackingCompany: string | null\n}\n\n/**\n * Retrieves tracking information for a fulfillment by its ID.\n * Returns the tracking numbers and the tracking company.\n *\n * @param {string | number | bigint} id - The Shopify fulfillment ID. Can be a GID string (e.g., \"gid://shopify/Fulfillment/123456789\") or a numeric ID (e.g., 123456789 or 123456789n).\n * @returns {Promise<FulfillmentTrackingIds | undefined>} A promise that resolves to the tracking info or undefined if fulfillment not found.\n * @throws {Error} If the GraphQL query fails.\n */\nexport async function getFulfillmentTrackingIds(\n id: string | number | bigint,\n): Promise<FulfillmentTrackingIds | undefined> {\n const gid =\n typeof id === 'string'\n ? id\n : convertIdIntoGid(\n typeof id === 'number' ? BigInt(id) : id,\n 'Fulfillment',\n )\n\n const variables: FulfillmentTrackingIdsQueryVariables = { id: gid }\n\n const response = await fetchShopifyGraphql<FulfillmentTrackingIdsQuery>({\n query: queryFulfillmentTrackingIds,\n variables,\n })\n\n if (!response.fulfillment) {\n logger.debug(`No fulfillment found with ID: ${id}`)\n return undefined\n }\n\n const trackingInfo = response.fulfillment.trackingInfo\n const trackingNumbers = trackingInfo\n .map((info) => info.number)\n .filter((num): num is string => num != null)\n // Use the first company found (typically all tracking numbers share the same company)\n const trackingCompany = trackingInfo[0]?.company ?? null\n\n return {\n trackingNumbers,\n trackingCompany,\n }\n}\n","import type {\n UpdateFulfillmentTrackingMutation,\n UpdateFulfillmentTrackingMutationVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { getFulfillmentTrackingIds } from '../../queries/fulfillments/getFulfillmentTrackingIds.js'\nimport { gql, logger } from '../../utils/logger.js'\nimport {\n convertIdIntoGid,\n fetchShopifyGraphql,\n} from '../../utils/shopifyFetch.js'\n\nexport type UpdateFulfillmentTrackingResult = {\n trackingNumbers: string[]\n trackingCompany: string | null\n}\n\nconst mutation = gql`#graphql\n mutation updateFulfillmentTracking(\n $fulfillmentId: ID!\n $trackingNumbers: [String!]!\n $company: String\n $notifyCustomer: Boolean\n ) {\n fulfillmentTrackingInfoUpdate(\n fulfillmentId: $fulfillmentId\n trackingInfoInput: { numbers: $trackingNumbers, company: $company }\n notifyCustomer: $notifyCustomer\n ) {\n fulfillment {\n trackingInfo {\n number\n company\n }\n }\n userErrors {\n field\n message\n }\n }\n }\n`\n\n/**\n * Adds a tracking number to an existing fulfillment.\n * Fetches existing tracking info and appends the new tracking number.\n *\n * @param fulfillmentId - The fulfillment ID (numeric, bigint, or GID string)\n * @param trackingNumber - The new tracking number to add\n * @param notifyCustomer - Whether to notify the customer (default: false)\n * @returns Promise resolving to the updated tracking info\n * @throws {ShopifyUserError} When the mutation fails\n * @throws {Error} When fulfillment not found or GraphQL errors occur\n *\n * @example\n * // Add tracking to fulfillment, don't notify customer yet\n * await updateFulfillmentTracking(123456789, 'TRACK123')\n *\n * // Add tracking and notify customer (e.g., last item in order)\n * await updateFulfillmentTracking(123456789, 'TRACK456', true)\n */\nexport async function updateFulfillmentTracking(\n fulfillmentId: number | bigint | string,\n trackingNumber: string,\n notifyCustomer = false,\n): Promise<UpdateFulfillmentTrackingResult> {\n const fulfillmentGid =\n typeof fulfillmentId === 'string'\n ? fulfillmentId\n : convertIdIntoGid(\n typeof fulfillmentId === 'number'\n ? BigInt(fulfillmentId)\n : fulfillmentId,\n 'Fulfillment',\n )\n\n logger.debug(`Updating tracking for fulfillment ${fulfillmentGid}`)\n\n const existingTracking = await getFulfillmentTrackingIds(fulfillmentGid)\n\n if (!existingTracking) {\n throw new Error(`Fulfillment not found: ${fulfillmentGid}`)\n }\n\n const updatedTrackingNumbers = existingTracking.trackingNumbers.includes(\n trackingNumber,\n )\n ? existingTracking.trackingNumbers\n : [...existingTracking.trackingNumbers, trackingNumber]\n\n const variables: UpdateFulfillmentTrackingMutationVariables = {\n fulfillmentId: fulfillmentGid,\n trackingNumbers: updatedTrackingNumbers,\n ...(existingTracking.trackingCompany\n ? { company: existingTracking.trackingCompany }\n : {}),\n notifyCustomer,\n }\n\n const result = await fetchShopifyGraphql<\n UpdateFulfillmentTrackingResult,\n UpdateFulfillmentTrackingMutation\n >({\n query: mutation,\n variables,\n dataExtractor: (data) => {\n if (!data.fulfillmentTrackingInfoUpdate) {\n throw new Error(\n \"GraphQL response missing 'fulfillmentTrackingInfoUpdate' field\",\n )\n }\n\n const fulfillment = data.fulfillmentTrackingInfoUpdate.fulfillment\n const trackingInfo = fulfillment?.trackingInfo ?? []\n const trackingNumbers = trackingInfo\n .map((info) => info.number)\n .filter((num): num is string => num != null)\n const trackingCompany = trackingInfo[0]?.company ?? null\n\n return {\n nodes: [{ trackingNumbers, trackingCompany }],\n userErrors: data.fulfillmentTrackingInfoUpdate.userErrors,\n }\n },\n })\n\n const trackingResult = result[0]\n if (!trackingResult) {\n throw new Error('Unexpected empty result from GraphQL mutation')\n }\n\n logger.debug(\n `Successfully updated tracking for fulfillment ${fulfillmentGid}`,\n )\n\n return trackingResult\n}\n","import type {\n OrderCancelMutation,\n OrderCancelMutationVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { gql, logger } from '../../utils/logger.js'\nimport {\n convertIdIntoGid,\n fetchShopifyGraphql,\n} from '../../utils/shopifyFetch.js'\n\ntype CancelOrderNode = { success: true }\n\nconst mutation = gql`#graphql\n mutation orderCancel($orderId: ID!) {\n orderCancel(\n orderId: $orderId\n refund: true\n restock: false\n reason: CUSTOMER\n notifyCustomer: true\n ) {\n orderCancelUserErrors {\n code\n field\n message\n }\n }\n }\n`\n\n/**\n * Cancel an order in Shopify.\n *\n * @param orderId - The order ID (numeric, bigint, or GID string)\n * @returns Promise resolving to true on success\n * @throws {ShopifyUserError} When cancellation fails (e.g., ORDER_ALREADY_CANCELLED)\n *\n * @example\n * // Success case\n * await cancelOrderById(12345678901234)\n *\n * // Error handling\n * import { ShopifyUserError } from '@ehrenkind/shopify-lib'\n * try {\n * await cancelOrderById(orderId)\n * } catch (error) {\n * if (error instanceof ShopifyUserError) {\n * const alreadyCancelled = error.errors.some(e => e.code === 'ORDER_ALREADY_CANCELLED')\n * }\n * }\n */\nexport async function cancelOrderById(\n orderId: number | bigint | string,\n): Promise<boolean> {\n const orderGid =\n typeof orderId === 'string'\n ? orderId\n : convertIdIntoGid(\n typeof orderId === 'number' ? BigInt(orderId) : orderId,\n 'Order',\n )\n\n logger.debug(`Cancelling order ${orderGid}`)\n\n const variables: OrderCancelMutationVariables = { orderId: orderGid }\n\n await fetchShopifyGraphql<CancelOrderNode, OrderCancelMutation>({\n query: mutation,\n variables,\n dataExtractor: (data) => {\n if (!data.orderCancel) {\n throw new Error(\"GraphQL response missing 'orderCancel' field\")\n }\n return {\n nodes: [{ success: true }],\n userErrors: data.orderCancel.orderCancelUserErrors,\n }\n },\n })\n\n logger.debug(`Order ${orderGid} cancelled successfully`)\n return true\n}\n","import type {\n CreateRefundMutation,\n CreateRefundMutationVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport {\n type CurrencyCode,\n OrderTransactionKind,\n type RefundLineItemRestockType,\n} from '../../generated-api-types/2025-04/admin.types.js'\nimport { gql, logger } from '../../utils/logger.js'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch.js'\n\nexport type CreateRefundLineItem = {\n lineItemId: number | bigint | string\n quantity: number\n restockType?: 'NO_RESTOCK' | 'CANCEL' | 'RETURN'\n locationId?: number | bigint | string\n}\n\nexport type CreateRefundTransaction = {\n amount: string\n gateway: string\n parentId?: number | bigint | string\n}\n\nexport type CreateRefundOptions = {\n currency?: CurrencyCode\n note?: string\n notify?: boolean\n refundLineItems?: CreateRefundLineItem[]\n shipping?: {\n fullRefund?: boolean\n amount?: string\n }\n transactions?: CreateRefundTransaction[]\n}\n\nexport type RefundMoney = {\n amount: string\n currencyCode: string\n}\n\nexport type CreateRefundResult = {\n id: string\n totalRefunded: {\n shopMoney: RefundMoney\n presentmentMoney: RefundMoney\n }\n}\n\nconst mutation = gql`#graphql\n mutation createRefund($input: RefundInput!) {\n refundCreate(input: $input) {\n refund {\n id\n totalRefundedSet {\n shopMoney {\n amount\n currencyCode\n }\n presentmentMoney {\n amount\n currencyCode\n }\n }\n }\n userErrors {\n field\n message\n }\n }\n }\n`\n\nfunction toGid(id: number | bigint | string, type: string): string {\n if (typeof id === 'string' && id.startsWith('gid://')) {\n return id\n }\n return `gid://shopify/${type}/${id}`\n}\n\n/**\n * Creates a refund for an order.\n *\n * @param orderId - The order ID (numeric, bigint, or GID string)\n * @param options - Refund configuration options\n * @returns Promise resolving to the created refund\n * @throws {ShopifyUserError} When the mutation fails\n * @throws {Error} When GraphQL errors occur\n *\n * @example\n * await createRefund(12345678901234, {\n * currency: 'EUR',\n * notify: true,\n * note: 'Customer return',\n * refundLineItems: [\n * { lineItemId: 111, quantity: 1, restockType: 'NO_RESTOCK' }\n * ],\n * transactions: [\n * { amount: '25.00', gateway: 'shopify_payments', parentId: 222 }\n * ]\n * })\n */\nexport async function createRefund(\n orderId: number | bigint | string,\n options: CreateRefundOptions = {},\n): Promise<CreateRefundResult> {\n const { currency, note, notify, refundLineItems, shipping, transactions } =\n options\n\n const orderGid = toGid(orderId, 'Order')\n\n logger.debug(`Creating refund for order ${orderGid}`)\n\n const variables: CreateRefundMutationVariables = {\n input: {\n orderId: orderGid,\n notify,\n ...(currency ? { currency } : {}),\n ...(note ? { note } : {}),\n ...(refundLineItems?.length\n ? {\n refundLineItems: refundLineItems.map((item) => ({\n lineItemId: toGid(item.lineItemId, 'LineItem'),\n quantity: item.quantity,\n ...(item.restockType\n ? { restockType: item.restockType as RefundLineItemRestockType }\n : {}),\n ...(item.locationId\n ? { locationId: toGid(item.locationId, 'Location') }\n : {}),\n })),\n }\n : {}),\n ...(shipping\n ? {\n shipping: {\n ...(shipping.fullRefund !== undefined\n ? { fullRefund: shipping.fullRefund }\n : {}),\n ...(shipping.amount ? { amount: shipping.amount } : {}),\n },\n }\n : {}),\n ...(transactions?.length\n ? {\n transactions: transactions.map((t) => ({\n amount: t.amount,\n gateway: t.gateway,\n kind: OrderTransactionKind.Refund,\n orderId: orderGid,\n ...(t.parentId\n ? { parentId: toGid(t.parentId, 'OrderTransaction') }\n : {}),\n })),\n }\n : {}),\n },\n }\n\n const result = await fetchShopifyGraphql<\n CreateRefundResult,\n CreateRefundMutation\n >({\n query: mutation,\n variables,\n dataExtractor: (data) => {\n if (!data.refundCreate) {\n throw new Error(\"GraphQL response missing 'refundCreate' field\")\n }\n\n const refund = data.refundCreate.refund\n if (!refund) {\n return {\n nodes: [],\n userErrors: data.refundCreate.userErrors,\n }\n }\n\n return {\n nodes: [\n {\n id: refund.id,\n totalRefunded: {\n shopMoney: {\n amount: refund.totalRefundedSet.shopMoney.amount,\n currencyCode: refund.totalRefundedSet.shopMoney.currencyCode,\n },\n presentmentMoney: {\n amount: refund.totalRefundedSet.presentmentMoney.amount,\n currencyCode:\n refund.totalRefundedSet.presentmentMoney.currencyCode,\n },\n },\n },\n ],\n userErrors: data.refundCreate.userErrors,\n }\n },\n })\n\n const refundResult = result[0]\n if (!refundResult) {\n throw new Error('Refund creation returned no result')\n }\n\n logger.debug(`Successfully created refund ${refundResult.id}`)\n\n return refundResult\n}\n","import type {\n BulkUpdateProductVariantsMutation,\n BulkUpdateProductVariantsMutationVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport type { ProductVariantsBulkInput } from '../../generated-api-types/2025-04/admin.types.js'\nimport { gql, logger } from '../../utils/logger.js'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch.js'\n\nexport type VariantUpdateInput = Omit<ProductVariantsBulkInput, 'id'> & {\n id: string\n}\n\nexport type BulkUpdateProductVariantsResult = {\n id: string\n sku: string | null\n}\n\nconst mutation = gql`#graphql\n mutation bulkUpdateProductVariants(\n $productId: ID!\n $variants: [ProductVariantsBulkInput!]!\n ) {\n productVariantsBulkUpdate(\n productId: $productId\n variants: $variants\n ) {\n productVariants {\n id\n sku\n }\n userErrors {\n code\n field\n message\n }\n }\n }\n`\n\n/**\n * Bulk updates product variants.\n *\n * @param productId - The product GID\n * @param variants - Array of variant updates (id required, plus fields to update)\n * @returns Array of updated variants with id and sku\n * @throws {ShopifyUserError} When the mutation fails\n */\nexport async function bulkUpdateProductVariants(\n productId: string,\n variants: VariantUpdateInput[],\n): Promise<BulkUpdateProductVariantsResult[]> {\n logger.debug(\n `Bulk updating ${variants.length} variants for product ${productId}`,\n )\n\n const variables: BulkUpdateProductVariantsMutationVariables = {\n productId,\n variants,\n }\n\n const result = await fetchShopifyGraphql<\n BulkUpdateProductVariantsResult,\n BulkUpdateProductVariantsMutation\n >({\n query: mutation,\n variables,\n dataExtractor: (data) => {\n if (!data.productVariantsBulkUpdate) {\n throw new Error(\n \"GraphQL response missing 'productVariantsBulkUpdate' field\",\n )\n }\n\n return {\n nodes: (data.productVariantsBulkUpdate.productVariants ?? []).map(\n (v) => ({\n id: v.id,\n sku: v.sku ?? null,\n }),\n ),\n userErrors: data.productVariantsBulkUpdate.userErrors,\n }\n },\n })\n\n logger.debug(`Successfully updated ${result.length} variants`)\n\n return result\n}\n","import type {\n UpsertMetaobjectMutation,\n UpsertMetaobjectMutationVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport type { MetaobjectFieldInput } from '../../generated-api-types/2025-04/admin.types.js'\nimport { gql, logger } from '../../utils/logger.js'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch.js'\n\nexport type UpsertMetaobjectInput = {\n type: string\n handle: string\n fields: MetaobjectFieldInput[]\n}\n\nexport type UpsertMetaobjectResult = {\n id: string\n handle: string\n displayName: string\n fields: Array<{ key: string; value: string | null }>\n}\n\nconst mutation = gql`#graphql\n mutation upsertMetaobject(\n $handle: MetaobjectHandleInput!\n $metaobject: MetaobjectUpsertInput!\n ) {\n metaobjectUpsert(handle: $handle, metaobject: $metaobject) {\n metaobject {\n id\n handle\n displayName\n fields {\n key\n value\n }\n }\n userErrors {\n code\n field\n message\n }\n }\n }\n`\n\n/**\n * Creates or updates a metaobject in Shopify based on its type and handle.\n *\n * @param input - The metaobject type, handle, and fields\n * @returns The created/updated metaobject\n * @throws {ShopifyUserError} When the upsert fails due to validation errors\n * @throws {Error} When GraphQL errors occur or no metaobject is returned\n */\nexport async function upsertMetaobject(\n input: UpsertMetaobjectInput,\n): Promise<UpsertMetaobjectResult> {\n const { type, handle, fields } = input\n\n logger.debug(`Upserting metaobject type=${type} handle=${handle}`)\n\n const variables: UpsertMetaobjectMutationVariables = {\n handle: { type, handle },\n metaobject: { fields },\n }\n\n const response = await fetchShopifyGraphql<\n UpsertMetaobjectResult,\n UpsertMetaobjectMutation\n >({\n query: mutation,\n variables,\n dataExtractor: (data) => {\n if (!data.metaobjectUpsert) {\n throw new Error(\"GraphQL response missing 'metaobjectUpsert' field\")\n }\n const { metaobject, userErrors } = data.metaobjectUpsert\n return {\n nodes: metaobject\n ? [\n {\n id: metaobject.id,\n handle: metaobject.handle,\n displayName: metaobject.displayName,\n fields: metaobject.fields.map((f) => ({\n key: f.key,\n value: f.value ?? null,\n })),\n },\n ]\n : [],\n userErrors,\n }\n },\n })\n\n const result = response[0]\n if (!result) {\n throw new Error('No metaobject returned from upsert operation')\n }\n logger.debug(`Metaobject upserted successfully: ${result.id}`)\n return result\n}\n","import { gql } from '../../utils/logger'\n\nexport const querySuggestedRefund = gql`#graphql\n query suggestedRefund(\n $orderId: ID!\n $refundLineItems: [RefundLineItemInput!]\n $refundShipping: Boolean\n $shippingAmount: Money\n $suggestFullRefund: Boolean\n ) {\n order(id: $orderId) {\n id\n name\n suggestedRefund(\n refundLineItems: $refundLineItems\n refundShipping: $refundShipping\n shippingAmount: $shippingAmount\n suggestFullRefund: $suggestFullRefund\n ) {\n amountSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n maximumRefundableSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n subtotalSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n totalTaxSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n discountedSubtotalSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n totalCartDiscountAmountSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n shipping {\n amountSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n maximumRefundableSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n }\n refundLineItems {\n lineItem {\n id\n sku\n title\n quantity\n }\n quantity\n priceSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n subtotalSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n totalTaxSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n restockType\n }\n suggestedTransactions {\n gateway\n kind\n amountSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n maximumRefundableSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n parentTransaction {\n id\n }\n }\n }\n }\n }\n`\n","import type {\n SuggestedRefundQuery,\n SuggestedRefundQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { RefundLineItemRestockType } from '../../generated-api-types/2025-04/admin.types.js'\nimport { logger } from '../../utils/logger.js'\nimport {\n convertIdIntoGid,\n fetchShopifyGraphql,\n} from '../../utils/shopifyFetch.js'\nimport { querySuggestedRefund } from './calculateRefund.queries.js'\n\n// Derive type from GraphQL response\nexport type SuggestedRefund = NonNullable<\n NonNullable<SuggestedRefundQuery['order']>['suggestedRefund']\n>\n\nexport interface CalculateRefundLineItem {\n lineItemId: number | bigint | string\n quantity: number\n restockType?: 'NO_RESTOCK' | 'CANCEL' | 'RETURN'\n locationId?: string\n}\n\nexport interface CalculateRefundOptions {\n refundLineItems?: CalculateRefundLineItem[]\n refundShipping?: boolean\n shippingAmount?: string\n suggestFullRefund?: boolean\n}\n\nfunction convertLineItemIdToGid(id: number | bigint | string): string {\n if (typeof id === 'string') {\n return id.startsWith('gid://') ? id : `gid://shopify/LineItem/${id}`\n }\n return `gid://shopify/LineItem/${id}`\n}\n\nfunction mapRestockType(\n restockType: 'NO_RESTOCK' | 'CANCEL' | 'RETURN' | undefined,\n): RefundLineItemRestockType {\n switch (restockType) {\n case 'CANCEL':\n return RefundLineItemRestockType.Cancel\n case 'RETURN':\n return RefundLineItemRestockType.Return\n default:\n return RefundLineItemRestockType.NoRestock\n }\n}\n\n/**\n * Calculate a suggested refund for an order.\n * Returns undefined if the order is not found or has no refundable items.\n *\n * @param orderId - The order ID (numeric, bigint, or GID string)\n * @param options - Options for the refund calculation\n * @returns The suggested refund or undefined\n */\nexport async function calculateRefund(\n orderId: number | bigint | string,\n options: CalculateRefundOptions = {},\n): Promise<SuggestedRefund | undefined> {\n const orderGid =\n typeof orderId === 'string'\n ? orderId\n : convertIdIntoGid(\n typeof orderId === 'number' ? BigInt(orderId) : orderId,\n 'Order',\n )\n\n const variables: SuggestedRefundQueryVariables = {\n orderId: orderGid,\n refundLineItems: options.refundLineItems?.map((item) => ({\n lineItemId: convertLineItemIdToGid(item.lineItemId),\n quantity: item.quantity,\n restockType: mapRestockType(item.restockType),\n ...(item.locationId ? { locationId: item.locationId } : {}),\n })),\n refundShipping: options.refundShipping,\n shippingAmount: options.shippingAmount,\n suggestFullRefund: options.suggestFullRefund,\n }\n\n const response = await fetchShopifyGraphql<SuggestedRefundQuery>({\n query: querySuggestedRefund,\n variables,\n })\n\n if (!response.order?.suggestedRefund) {\n logger.debug(`No refund suggestion available for order: ${orderId}`)\n return undefined\n }\n\n return response.order.suggestedRefund\n}\n","import z from 'zod'\nimport type {\n OrderByIdFullQuery,\n OrderByIdQuery,\n OrderByIdQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { logger } from '../../utils/logger.js'\nimport {\n convertIdIntoGid,\n fetchShopifyGraphql,\n} from '../../utils/shopifyFetch.js'\nimport { returnOutputParsed } from '../../utils/zod.js'\nimport { queryOrderById, queryOrderByIdFull } from './getOrderById.queries.js'\n\n// Address schema (shared between lean and full)\nconst AddressSchema = z\n .object({\n firstName: z.string().nullable(),\n lastName: z.string().nullable(),\n address1: z.string().nullable(),\n address2: z.string().nullable(),\n city: z.string().nullable(),\n province: z.string().nullable(),\n country: z.string().nullable(),\n zip: z.string().nullable(),\n })\n .nullable()\n\n// Lean order schema\nconst GetLeanOrderByIdReturn = z.object({\n id: z.string(),\n name: z.string(),\n createdAt: z.string(),\n updatedAt: z.string(),\n cancelledAt: z.string().nullable(),\n cancelReason: z.string().nullable(),\n totalPrice: z.object({\n amount: z.string(),\n currencyCode: z.string(),\n }),\n customer: z\n .object({\n id: z.string(),\n displayName: z.string(),\n firstName: z.string().nullable(),\n lastName: z.string().nullable(),\n emailAddress: z.string().nullable(),\n })\n .nullable(),\n financialStatus: z.string().nullable(),\n fulfillmentStatus: z.string().nullable(),\n shippingAddress: AddressSchema,\n})\n\nexport type LeanOrder = z.infer<typeof GetLeanOrderByIdReturn> | undefined\n\n// Full order type - derived from the generated GraphQL types\nexport type FullOrder = NonNullable<OrderByIdFullQuery['order']>\n\ntype OrderDetailLevel = 'lean' | 'full'\n\n// Function overloads\nexport function getOrderById(id: number | bigint): Promise<LeanOrder>\nexport function getOrderById(\n id: number | bigint,\n detailLevel: 'lean',\n): Promise<LeanOrder>\nexport function getOrderById(\n id: number | bigint,\n detailLevel: 'full',\n): Promise<FullOrder | undefined>\n\n/**\n * Retrieves a single order from Shopify by its numeric ID.\n * Returns undefined if no order is found with the specified ID.\n *\n * @param {number | bigint} id - The numerical Shopify order ID (e.g., 12345678 or 12345678n).\n * @param {OrderDetailLevel} detailLevel - The level of detail to return ('lean' or 'full'). Defaults to 'lean'.\n * @returns {Promise<LeanOrder | FullOrder>} A promise that resolves to the order data or undefined if not found.\n * @throws {Error} If the GraphQL query fails or if the response structure is invalid.\n */\nexport async function getOrderById(\n id: number | bigint,\n detailLevel: OrderDetailLevel = 'lean',\n): Promise<LeanOrder | FullOrder> {\n const bigIntId = typeof id === 'number' ? BigInt(id) : id\n if (detailLevel === 'lean') {\n return getLeanOrderById(bigIntId)\n }\n return getFullOrderById(bigIntId)\n}\n\nasync function getLeanOrderById(id: bigint): Promise<LeanOrder> {\n const variables: OrderByIdQueryVariables = {\n id: convertIdIntoGid(id, 'Order'),\n }\n\n const response = await fetchShopifyGraphql<OrderByIdQuery>({\n query: queryOrderById,\n variables,\n })\n\n if (!response.order) {\n logger.debug(`No order found with ID: ${id}`)\n return undefined\n }\n\n const order = response.order\n\n const leanOrder = {\n id: order.id,\n name: order.name,\n createdAt: order.createdAt,\n updatedAt: order.updatedAt,\n cancelledAt: order.cancelledAt ?? null,\n cancelReason: order.cancelReason ?? null,\n totalPrice: {\n amount: order.totalPriceSet?.shopMoney?.amount ?? '',\n currencyCode: order.totalPriceSet?.shopMoney?.currencyCode ?? '',\n },\n customer: order.customer\n ? {\n id: order.customer.id,\n displayName: order.customer.displayName,\n firstName: order.customer.firstName ?? null,\n lastName: order.customer.lastName ?? null,\n emailAddress:\n order.customer.defaultEmailAddress?.emailAddress ?? null,\n }\n : null,\n financialStatus: order.displayFinancialStatus ?? null,\n fulfillmentStatus: order.displayFulfillmentStatus ?? null,\n shippingAddress: order.shippingAddress\n ? {\n firstName: order.shippingAddress.firstName ?? null,\n lastName: order.shippingAddress.lastName ?? null,\n address1: order.shippingAddress.address1 ?? null,\n address2: order.shippingAddress.address2 ?? null,\n city: order.shippingAddress.city ?? null,\n province: order.shippingAddress.province ?? null,\n country: order.shippingAddress.country ?? null,\n zip: order.shippingAddress.zip ?? null,\n }\n : null,\n }\n\n return await returnOutputParsed(leanOrder, GetLeanOrderByIdReturn)\n}\n\nasync function getFullOrderById(id: bigint): Promise<FullOrder | undefined> {\n const variables: OrderByIdQueryVariables = {\n id: convertIdIntoGid(id, 'Order'),\n }\n\n const response = await fetchShopifyGraphql<OrderByIdFullQuery>({\n query: queryOrderByIdFull,\n variables,\n })\n\n if (!response.order) {\n logger.debug(`No order found with ID: ${id}`)\n return undefined\n }\n\n return response.order\n}\n","import z from 'zod'\nimport { logger } from './logger.js'\n\nexport async function returnOutputParsed<T>(\n data: unknown,\n Model: z.ZodType<T>,\n) {\n const parsed = await Model.safeParseAsync(data)\n if (!parsed.success) {\n if (parsed.error instanceof z.ZodError) {\n const msg = JSON.stringify(parsed.error.format(), null, 2)\n logger.error(msg)\n } else {\n logger.error('Failed to parse:', parsed.error)\n }\n // throw parsedVariants.error\n throw new Error('Failed to parse product variants')\n }\n logger.info('Parsed data successfully')\n return parsed.data\n}\n","import { gql } from '../../utils/logger'\n\nexport const queryOrderById = gql`#graphql\n query orderById($id: ID!) {\n order(id: $id) {\n id\n name\n createdAt\n updatedAt\n cancelledAt\n cancelReason\n totalPriceSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n customer {\n id\n lastName\n defaultEmailAddress {\n emailAddress\n }\n displayName\n firstName\n }\n displayFinancialStatus\n displayFulfillmentStatus\n shippingAddress {\n firstName\n lastName\n address1\n address2\n city\n province\n country\n zip\n }\n }\n }\n`\n\nexport const queryOrderByIdFull = gql`#graphql\n query orderByIdFull($id: ID!) {\n order(id: $id) {\n id\n name\n createdAt\n updatedAt\n processedAt\n closedAt\n cancelledAt\n cancelReason\n totalPriceSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n customer {\n id\n firstName\n lastName\n email\n phone\n }\n displayFinancialStatus\n displayFulfillmentStatus\n shippingAddress {\n firstName\n lastName\n address1\n address2\n city\n province\n country\n zip\n }\n billingAddress {\n firstName\n lastName\n address1\n address2\n city\n province\n country\n zip\n }\n lineItems(first: 100) {\n edges {\n node {\n id\n sku\n title\n variantTitle\n quantity\n customAttributes {\n key\n value\n }\n originalUnitPriceSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n vendor\n image {\n url\n width\n height\n altText\n }\n }\n }\n }\n fulfillments {\n id\n name\n totalQuantity\n status\n createdAt\n estimatedDeliveryAt\n deliveredAt\n trackingInfo {\n company\n number\n url\n }\n fulfillmentLineItems(first: 100) {\n edges {\n node {\n id\n quantity\n lineItem {\n id\n sku\n }\n }\n }\n }\n }\n shippingLine {\n originalPriceSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n }\n taxLines {\n priceSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n }\n totalDiscountsSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n discountCodes\n refunds {\n totalRefundedSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n }\n }\n }\n`\n","import z from 'zod'\nimport type {\n OrdersByNameFullQuery,\n OrdersByNameQuery,\n OrdersByNameQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { logger } from '../../utils/logger.js'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch.js'\nimport { returnOutputParsed } from '../../utils/zod.js'\nimport {\n queryOrdersByName,\n queryOrdersByNameFull,\n} from './getOrderByName.queries.js'\n\nconst GetLeanOrderByNameReturn = z.object({\n id: z.string(),\n name: z.string(),\n createdAt: z.string(),\n updatedAt: z.string(),\n totalPrice: z.object({\n amount: z.string(),\n currencyCode: z.string(),\n }),\n customer: z\n .object({\n id: z.string(),\n displayName: z.string(),\n emailAddress: z.string().nullable(),\n })\n .nullable(),\n financialStatus: z.string().nullable(),\n fulfillmentStatus: z.string().nullable(),\n})\n\nexport type LeanOrderByName =\n | z.infer<typeof GetLeanOrderByNameReturn>\n | undefined\n\nexport type FullOrderByName =\n | NonNullable<\n NonNullable<OrdersByNameFullQuery['orders']>['edges'][number]['node']\n >\n | undefined\n\ntype OrderDetailLevel = 'lean' | 'full'\n\n// Function overloads\nexport function getOrderByName(\n orderName: string,\n detailLevel: 'lean',\n): Promise<LeanOrderByName>\nexport function getOrderByName(\n orderName: string,\n detailLevel: 'full',\n): Promise<FullOrderByName>\nexport function getOrderByName(orderName: string): Promise<LeanOrderByName>\n\n/**\n * Retrieves a single order from Shopify by its order name (e.g., \"B12345\").\n * Returns undefined if no order is found with the specified name.\n *\n * @param {string} orderName - The order name to search for (e.g., \"B12345\").\n * @param {OrderDetailLevel} detailLevel - The level of detail to return ('lean' or 'full'). Defaults to 'lean'.\n * @returns {Promise<LeanOrderByName | FullOrderByName>} A promise that resolves to the order data or undefined if not found.\n * @throws {Error} If the GraphQL query fails or if the response structure is invalid.\n */\nexport async function getOrderByName(\n orderName: string,\n detailLevel: OrderDetailLevel = 'lean',\n): Promise<LeanOrderByName | FullOrderByName> {\n if (detailLevel === 'lean') {\n return getLeanOrderByName(orderName)\n }\n return getFullOrderByName(orderName)\n}\n\nasync function getLeanOrderByName(orderName: string): Promise<LeanOrderByName> {\n const variables: OrdersByNameQueryVariables = {\n first: 1,\n queryFilter: `name:${orderName}`,\n }\n\n type SingleNode = NonNullable<\n NonNullable<OrdersByNameQuery['orders']>['edges'][number]['node']\n >\n\n const extractedNodes = await fetchShopifyGraphql<\n SingleNode,\n OrdersByNameQuery\n >({\n query: queryOrdersByName,\n variables,\n dataExtractor: (pageData: OrdersByNameQuery) => {\n if (!pageData.orders) {\n throw new Error(\n \"GraphQL response for orders is missing the 'orders' field.\",\n )\n }\n const nodes: SingleNode[] = pageData.orders.edges.map(\n (edge: { node: SingleNode }) => edge.node,\n )\n return {\n nodes,\n }\n },\n fetchAllPages: false,\n })\n\n const order = extractedNodes[0]\n if (!order) {\n logger.debug(`No order found with name: ${orderName}`)\n return undefined\n }\n\n const leanOrder = {\n id: order.id,\n name: order.name,\n createdAt: order.createdAt,\n updatedAt: order.updatedAt,\n totalPrice: {\n amount: order.totalPriceSet?.shopMoney?.amount ?? '',\n currencyCode: order.totalPriceSet?.shopMoney?.currencyCode ?? '',\n },\n customer: order.customer\n ? {\n id: order.customer.id,\n displayName: order.customer.displayName,\n emailAddress:\n order.customer.defaultEmailAddress?.emailAddress ?? null,\n }\n : null,\n financialStatus: order.displayFinancialStatus ?? null,\n fulfillmentStatus: order.displayFulfillmentStatus ?? null,\n }\n\n return await returnOutputParsed(leanOrder, GetLeanOrderByNameReturn)\n}\n\nasync function getFullOrderByName(orderName: string): Promise<FullOrderByName> {\n const variables: OrdersByNameQueryVariables = {\n first: 1,\n queryFilter: `name:${orderName}`,\n }\n\n type SingleNode = NonNullable<\n NonNullable<OrdersByNameFullQuery['orders']>['edges'][number]['node']\n >\n\n const extractedNodes = await fetchShopifyGraphql<\n SingleNode,\n OrdersByNameFullQuery\n >({\n query: queryOrdersByNameFull,\n variables,\n dataExtractor: (pageData: OrdersByNameFullQuery) => {\n if (!pageData.orders) {\n throw new Error(\n \"GraphQL response for orders is missing the 'orders' field.\",\n )\n }\n const nodes: SingleNode[] = pageData.orders.edges.map(\n (edge: { node: SingleNode }) => edge.node,\n )\n return {\n nodes,\n }\n },\n fetchAllPages: false,\n })\n\n if (extractedNodes.length === 0) {\n logger.debug(`No order found with name: ${orderName}`)\n return undefined\n }\n\n const order = extractedNodes[0]\n if (!order) {\n logger.debug(`No order found with name: ${orderName}`)\n return undefined\n }\n\n return order\n}\n","import { gql } from '../../utils/logger'\n\nexport const queryOrdersByName = gql`#graphql\n query ordersByName($first: Int!, $queryFilter: String!) {\n orders(first: $first, query: $queryFilter) {\n edges {\n node {\n id\n name\n createdAt\n updatedAt\n totalPriceSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n customer {\n id\n lastName\n defaultEmailAddress {\n emailAddress\n }\n displayName\n firstName\n }\n displayFinancialStatus\n displayFulfillmentStatus\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n`\n\nexport const queryOrdersByNameFull = gql`#graphql\n query ordersByNameFull($first: Int!, $queryFilter: String!) {\n orders(first: $first, query: $queryFilter) {\n edges {\n node {\n billingAddress {\n address1\n address2\n city\n company\n country\n countryCodeV2\n firstName\n formattedArea\n id\n lastName\n name\n phone\n province\n provinceCode\n timeZone\n zip\n }\n billingAddressMatchesShippingAddress\n cancelReason\n cancellation {\n staffNote\n }\n cancelledAt\n capturable\n clientIp\n closed\n closedAt\n confirmed\n createdAt\n currencyCode\n currentCartDiscountAmountSet {\n presentmentMoney {\n amount\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n currentShippingPriceSet {\n presentmentMoney {\n amount\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n currentSubtotalLineItemsQuantity\n currentSubtotalPriceSet {\n presentmentMoney {\n amount\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n currentTaxLines {\n channelLiable\n rate\n ratePercentage\n source\n title\n priceSet {\n presentmentMoney {\n amount\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n }\n currentTotalAdditionalFeesSet {\n presentmentMoney {\n amount\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n currentTotalDiscountsSet {\n presentmentMoney {\n amount\n currencyCode\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n currentTotalDutiesSet {\n presentmentMoney {\n amount\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n currentTotalPriceSet {\n presentmentMoney {\n amount\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n currentTotalTaxSet {\n presentmentMoney {\n amount\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n currentTotalWeight\n customer {\n id\n lastName\n defaultEmailAddress {\n emailAddress\n }\n displayName\n firstName\n }\n customerAcceptsMarketing\n discountCodes\n discountCode\n displayAddress {\n address1\n address2\n city\n company\n country\n countryCodeV2\n firstName\n formattedArea\n id\n lastName\n name\n phone\n province\n provinceCode\n timeZone\n zip\n }\n displayFinancialStatus\n displayFulfillmentStatus\n dutiesIncluded\n edited\n email\n estimatedTaxes\n fulfillable\n fulfillments(first: 20) {\n createdAt\n deliveredAt\n displayStatus\n estimatedDeliveryAt\n updatedAt\n trackingInfo(first: 10) {\n company\n url\n }\n totalQuantity\n status\n name\n id\n }\n fullyPaid\n id\n lineItems(first: 50) {\n edges {\n node {\n id\n name\n originalUnitPriceSet {\n presentmentMoney {\n amount\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n quantity\n requiresShipping\n sku\n title\n variantTitle\n }\n }\n }\n name\n note\n processedAt\n shippingAddress {\n address1\n address2\n city\n company\n country\n countryCodeV2\n firstName\n formattedArea\n id\n lastName\n name\n phone\n province\n provinceCode\n timeZone\n zip\n }\n statusPageUrl\n tags\n totalPriceSet {\n presentmentMoney {\n amount\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n totalReceivedSet {\n presentmentMoney {\n amount\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n totalRefundedSet {\n presentmentMoney {\n amount\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n totalShippingPriceSet {\n presentmentMoney {\n amount\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n totalTaxSet {\n presentmentMoney {\n amount\n currencyCode\n }\n shopMoney {\n amount\n currencyCode\n }\n }\n totalWeight\n unpaid\n updatedAt\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n`\n","import { gql } from '../../utils/logger'\n\nexport const queryOrderCancellationInfoByName = gql`#graphql\n query orderCancellationInfoByName($first: Int!, $queryFilter: String!) {\n orders(first: $first, query: $queryFilter) {\n edges {\n node {\n id\n name\n cancelledAt\n }\n }\n }\n }\n`\n","import type {\n OrderCancellationInfoByNameQuery,\n OrderCancellationInfoByNameQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { logger } from '../../utils/logger.js'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch.js'\nimport { queryOrderCancellationInfoByName } from './getOrderCancellationInfo.queries.js'\n\n// OrderCancellationInfo type - derived from the generated GraphQL types\nexport type OrderCancellationInfo = NonNullable<\n OrderCancellationInfoByNameQuery['orders']['edges'][number]['node']\n>\n\n/**\n * Retrieves cancellation information for an order by its name (e.g., \"B12345\").\n * Returns undefined if no order is found with the specified name.\n *\n * @param {string} orderName - The order name to search for (e.g., \"B12345\").\n * @returns {Promise<OrderCancellationInfo | undefined>} A promise that resolves to the order cancellation info or undefined if not found.\n * @throws {Error} If the GraphQL query fails or if the response structure is invalid.\n */\nexport async function getOrderCancellationInfoByName(\n orderName: string,\n): Promise<OrderCancellationInfo | undefined> {\n const variables: OrderCancellationInfoByNameQueryVariables = {\n first: 1,\n queryFilter: `name:${orderName}`,\n }\n\n const response = await fetchShopifyGraphql<OrderCancellationInfoByNameQuery>({\n query: queryOrderCancellationInfoByName,\n variables,\n })\n\n if (!response.orders) {\n throw new Error(\n \"Invalid GraphQL response for getOrderCancellationInfoByName: 'orders' field is missing.\",\n )\n }\n\n if (!Array.isArray(response.orders.edges)) {\n throw new Error(\n \"Invalid GraphQL response for getOrderCancellationInfoByName: 'orders.edges' is not an array.\",\n )\n }\n\n const firstEdge = response.orders.edges[0]\n const order = firstEdge?.node\n\n if (!order) {\n logger.debug(`No order found with name: ${orderName}`)\n return undefined\n }\n\n return order\n}\n","import z from 'zod'\nimport type {\n LeanProductVariantsQuery,\n LeanProductVariantsQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { gql, logger } from '../../utils/logger.js'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch.js'\nimport { returnOutputParsed } from '../../utils/zod.js'\n\nconst GetLeanProductVariantsReturn = z.array(\n z.object({\n productId: z.string(),\n productTitle: z.string(),\n variantId: z.string(),\n variantTitle: z.string(),\n sku: z.string(),\n status: z.enum(['ACTIVE', 'ARCHIVED', 'DRAFT']),\n }),\n)\n\nexport type LeanProductVariant = z.infer<\n typeof GetLeanProductVariantsReturn\n>[number]\n\nexport type LeanProductVariantsOptions = {\n /** Filter to only active/draft products (excludes ARCHIVED). Defaults to false. */\n activeOnly?: boolean\n}\n\n/**\n * Retrieves a lean list of product variants from Shopify, optionally filtered by SKUs.\n * Product variants are mapped to a simpler output structure.\n * Variants missing essential properties (e.g., SKU) will be filtered out and logged.\n *\n * @param {string[]} [skus] - An optional array of SKUs to filter by. If provided, only variants matching these SKUs will be fetched.\n * @param {LeanProductVariantsOptions} [options] - Optional settings.\n * @param {boolean} [options.activeOnly=false] - If true, excludes ARCHIVED products at query level.\n * @returns {Promise<LeanProductVariant[]>} A promise that resolves to an array of lean product variant data.\n * @throws {Error} If the GraphQL query fails, returns no data, or if the `productVariants` field is missing in the response.\n */\nexport async function getLeanProductVariants(\n skus?: string[],\n options?: LeanProductVariantsOptions,\n): Promise<LeanProductVariant[]> {\n const queryGql = gql`#graphql\n query leanProductVariants($first: Int!, $after: String, $queryFilter: String) {\n productVariants(first: $first, after: $after, query: $queryFilter) {\n edges {\n node {\n id\n title\n sku\n product {\n id\n title\n status\n }\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n `\n\n const queryParts: string[] = []\n if (skus && skus.length > 0) {\n queryParts.push(skus.map((sku: string) => `sku:${sku}`).join(' OR '))\n }\n if (options?.activeOnly) {\n queryParts.push('product_status:active,draft')\n }\n\n const initialVariables: LeanProductVariantsQueryVariables = {\n first: 250,\n ...(queryParts.length > 0 && {\n queryFilter: queryParts.filter(Boolean).join(' AND '),\n }),\n }\n\n // Type for a single node from the productVariants query\n type SingleNode = NonNullable<\n NonNullable<\n LeanProductVariantsQuery['productVariants']\n >['edges'][number]['node']\n >\n\n const extractedNodes = await fetchShopifyGraphql<\n SingleNode,\n LeanProductVariantsQuery\n >({\n query: queryGql,\n variables: initialVariables,\n dataExtractor: (pageData: LeanProductVariantsQuery) => {\n if (!pageData.productVariants) {\n throw new Error(\n \"GraphQL response for product variants is missing the 'productVariants' field.\",\n )\n }\n const nodes: SingleNode[] = pageData.productVariants.edges.map(\n (edge: { node: SingleNode }) => edge.node,\n )\n return {\n nodes,\n pageInfo: pageData.productVariants.pageInfo,\n }\n },\n fetchAllPages: true,\n })\n\n const allVariants = extractedNodes.flatMap<LeanProductVariant>((v) => {\n if (v.sku) {\n return [\n {\n productId: v.product.id,\n productTitle: v.product.title,\n variantId: v.id,\n variantTitle: v.title,\n sku: v.sku,\n status: v.product.status,\n },\n ]\n }\n logger.debug(\n `Product ${v.product.title} (ID: ${v.product.id}) has a variant (ID: ${v.id}) with no SKU. Filtering out.`,\n )\n return []\n })\n\n return await returnOutputParsed(allVariants, GetLeanProductVariantsReturn)\n}\n","import z from 'zod'\nimport type {\n ProductVariantsBySkusQuery,\n ProductVariantsBySkusQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { gql, logger } from '../../utils/logger.js'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch.js'\nimport { returnOutputParsed } from '../../utils/zod.js'\n\nconst GetProductVariantsBySkusReturn = z.array(\n z.object({\n productId: z.string(),\n productTitle: z.string(),\n variantId: z.string(),\n variantTitle: z.string(),\n sku: z.string(),\n status: z.enum(['ACTIVE', 'ARCHIVED', 'DRAFT']),\n }),\n)\n\nexport type ProductVariantBySku = z.infer<\n typeof GetProductVariantsBySkusReturn\n>[number]\n\nexport type ProductVariantsBySkusOptions = {\n /** Filter to only active products (excludes ARCHIVED). Defaults to false. */\n activeOnly?: boolean\n}\n\n/**\n * Retrieves product variants from Shopify filtered by SKUs.\n * Variants missing a SKU will be filtered out and logged.\n *\n * @param {string[]} skus - Array of SKUs to filter by.\n * @param {ProductVariantsBySkusOptions} [options] - Optional settings.\n * @param {boolean} [options.activeOnly=false] - If true, excludes ARCHIVED products at query level.\n * @returns {Promise<ProductVariantBySku[]>} A promise that resolves to an array of product variant data.\n * @throws {Error} If the GraphQL query fails or returns no data.\n */\nexport async function getProductVariantsBySkus(\n skus: string[],\n options?: ProductVariantsBySkusOptions,\n): Promise<ProductVariantBySku[]> {\n if (skus.length === 0) {\n return []\n }\n\n const queryGql = gql`#graphql\n query productVariantsBySkus($first: Int!, $after: String, $queryFilter: String) {\n productVariants(first: $first, after: $after, query: $queryFilter) {\n edges {\n node {\n id\n title\n sku\n product {\n id\n title\n status\n }\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n `\n\n const skuFilter = skus.map((sku: string) => `sku:${sku}`).join(' OR ')\n const statusFilter = options?.activeOnly ? 'product_status:active,draft' : ''\n const queryFilter = [skuFilter, statusFilter].filter(Boolean).join(' AND ')\n\n const initialVariables: ProductVariantsBySkusQueryVariables = {\n first: 250,\n queryFilter,\n }\n\n type SingleNode = NonNullable<\n NonNullable<\n ProductVariantsBySkusQuery['productVariants']\n >['edges'][number]['node']\n >\n\n const extractedNodes = await fetchShopifyGraphql<\n SingleNode,\n ProductVariantsBySkusQuery\n >({\n query: queryGql,\n variables: initialVariables,\n dataExtractor: (pageData: ProductVariantsBySkusQuery) => {\n if (!pageData.productVariants) {\n throw new Error(\n \"GraphQL response for product variants is missing the 'productVariants' field.\",\n )\n }\n const nodes: SingleNode[] = pageData.productVariants.edges.map(\n (edge: { node: SingleNode }) => edge.node,\n )\n return {\n nodes,\n pageInfo: pageData.productVariants.pageInfo,\n }\n },\n fetchAllPages: true,\n })\n\n const allVariants = extractedNodes.flatMap<ProductVariantBySku>((v) => {\n if (!v.sku) {\n logger.debug(\n `Product ${v.product.title} (ID: ${v.product.id}) has a variant (ID: ${v.id}) with no SKU. Filtering out.`,\n )\n return []\n }\n return [\n {\n productId: v.product.id,\n productTitle: v.product.title,\n variantId: v.id,\n variantTitle: v.title,\n sku: v.sku,\n status: v.product.status,\n },\n ]\n })\n\n return await returnOutputParsed(allVariants, GetProductVariantsBySkusReturn)\n}\n","import z from 'zod'\nimport type {\n AllProductVariantsQuery,\n AllProductVariantsQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { logger } from '../../utils/logger.js'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch.js'\nimport { returnOutputParsed } from '../../utils/zod.js'\nimport { queryAllProductVariants } from './getAllProductVariants.queries.js'\n\nconst ProductVariantSchema = z.object({\n status: z.enum(['ACTIVE', 'ARCHIVED', 'DRAFT']),\n sku: z.string(),\n barcode: z.string().nullable(),\n price: z.string(),\n title: z.string(),\n url: z.string().nullable(),\n handle: z.string(),\n description: z.string(),\n imageUrl: z.string().nullable(),\n inventoryQuantity: z.number(),\n})\n\nconst GetAllProductVariantsReturn = z.array(ProductVariantSchema)\n\nexport type ProductVariant = z.infer<typeof ProductVariantSchema>\n\n/**\n * Retrieves all product variants from Shopify with full details.\n * Automatically handles pagination to fetch all variants.\n *\n * Each variant includes product info with combined title (product + variant title\n * when variant title is not \"Default Title\"), URL with variant ID, and inventory data.\n *\n * @returns {Promise<ProductVariant[]>} A promise that resolves to an array of product variants.\n * @throws {Error} If the GraphQL query fails or if the response is missing expected data.\n */\nexport async function getAllProductVariants(): Promise<ProductVariant[]> {\n const initialVariables: AllProductVariantsQueryVariables = { first: 250 }\n\n // Type for a single node from the productVariants query\n type SingleNode = NonNullable<\n NonNullable<\n AllProductVariantsQuery['productVariants']\n >['edges'][number]['node']\n >\n\n const extractedNodes = await fetchShopifyGraphql<\n SingleNode,\n AllProductVariantsQuery\n >({\n query: queryAllProductVariants,\n variables: initialVariables,\n dataExtractor: (pageData: AllProductVariantsQuery) => {\n if (!pageData.productVariants) {\n throw new Error(\n \"GraphQL response for product variants is missing the 'productVariants' field.\",\n )\n }\n const nodes: SingleNode[] = pageData.productVariants.edges.map(\n (edge: { node: SingleNode }) => edge.node,\n )\n return {\n nodes,\n pageInfo: pageData.productVariants.pageInfo,\n }\n },\n fetchAllPages: true,\n })\n\n logger.debug(`Fetched ${extractedNodes.length} product variants from Shopify`)\n\n const allVariants = extractedNodes.map<ProductVariant>((v) => {\n // Combine product title + variant title (unless \"Default Title\")\n const title =\n v.title === 'Default Title'\n ? v.product.title\n : `${v.product.title} ${v.title}`\n\n // Build URL with variant ID (using legacyResourceId)\n const url = v.product.onlineStoreUrl\n ? `${v.product.onlineStoreUrl}?variant=${v.legacyResourceId}`\n : null\n\n return {\n status: v.product.status,\n sku: v.sku ?? '',\n barcode: v.barcode ?? null,\n price: v.price,\n title,\n url,\n handle: v.product.handle,\n description: v.product.description,\n imageUrl: v.product.featuredImage?.url ?? null,\n inventoryQuantity: v.inventoryQuantity ?? 0,\n }\n })\n\n return await returnOutputParsed(allVariants, GetAllProductVariantsReturn)\n}\n","import { gql } from '../../utils/logger.js'\n\nexport const queryAllProductVariants = gql`#graphql\n query allProductVariants($first: Int!, $after: String) {\n productVariants(first: $first, after: $after) {\n edges {\n node {\n id\n legacyResourceId\n sku\n barcode\n inventoryQuantity\n price\n title\n product {\n status\n title\n description\n handle\n onlineStoreUrl\n featuredImage {\n url\n }\n }\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n`\n","import { gql } from '../../utils/logger.js'\n\nexport const queryOrderPaymentDetails = gql`#graphql\n query orderPaymentDetailsById($id: ID!) {\n order(id: $id) {\n transactions {\n amountSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n createdAt\n gateway\n formattedGateway\n kind\n paymentId\n }\n }\n }\n`\n","import type {\n OrderPaymentDetailsByIdQuery,\n OrderPaymentDetailsByIdQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { logger } from '../../utils/logger.js'\nimport {\n convertIdIntoGid,\n fetchShopifyGraphql,\n} from '../../utils/shopifyFetch.js'\nimport { queryOrderPaymentDetails } from './getOrderPaymentDetails.queries.js'\n\nexport type OrderPaymentDetails = NonNullable<\n OrderPaymentDetailsByIdQuery['order']\n>\n\n/**\n * Retrieves payment details for a single order from Shopify by its ID.\n * Returns undefined if no order is found with the specified ID.\n *\n * @param {bigint} id - The numerical Shopify order ID (e.g., 12345678n).\n * @returns {Promise<OrderPaymentDetails | undefined>} A promise that resolves to the order payment data or undefined if not found.\n * @throws {Error} If the GraphQL query fails.\n */\nexport async function getOrderPaymentDetailsById(\n id: bigint,\n): Promise<OrderPaymentDetails | undefined> {\n const variables: OrderPaymentDetailsByIdQueryVariables = {\n id: convertIdIntoGid(id, 'Order'),\n }\n\n const response = await fetchShopifyGraphql<OrderPaymentDetailsByIdQuery>({\n query: queryOrderPaymentDetails,\n variables,\n })\n\n if (!response.order) {\n logger.debug(`No order found with ID: ${id}`)\n return undefined\n }\n\n return response.order\n}\n","import { gql } from '../../utils/logger'\n\nexport const queryFulfillmentById = gql`#graphql\n query fulfillmentById($id: ID!) {\n fulfillment(id: $id) {\n id\n name\n createdAt\n updatedAt\n status\n totalQuantity\n estimatedDeliveryAt\n deliveredAt\n location {\n id\n legacyResourceId\n name\n }\n service {\n handle\n serviceName\n }\n trackingInfo(first: 10) {\n company\n number\n url\n }\n originAddress {\n address1\n address2\n city\n countryCode\n provinceCode\n zip\n }\n fulfillmentLineItems(first: 100) {\n edges {\n node {\n id\n quantity\n originalTotalSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n lineItem {\n id\n title\n sku\n variant {\n id\n }\n }\n }\n }\n }\n }\n }\n`\n","import type {\n FulfillmentByIdQuery,\n FulfillmentByIdQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { logger } from '../../utils/logger.js'\nimport {\n convertIdIntoGid,\n fetchShopifyGraphql,\n} from '../../utils/shopifyFetch.js'\nimport { queryFulfillmentById } from './getFulfillmentById.queries.js'\n\n// Fulfillment type - derived from the generated GraphQL types\nexport type Fulfillment = NonNullable<FulfillmentByIdQuery['fulfillment']>\n\n/**\n * Retrieves a single fulfillment from Shopify by its ID.\n * Returns undefined if no fulfillment is found with the specified ID.\n *\n * @param {string | number | bigint} id - The Shopify fulfillment ID. Can be a GID string (e.g., \"gid://shopify/Fulfillment/123456789\") or a numeric ID (e.g., 123456789 or 123456789n).\n * @returns {Promise<Fulfillment | undefined>} A promise that resolves to the fulfillment data or undefined if not found.\n * @throws {Error} If the GraphQL query fails or if the response structure is invalid.\n */\nexport async function getFulfillmentById(\n id: string | number | bigint,\n): Promise<Fulfillment | undefined> {\n const gid =\n typeof id === 'string'\n ? id\n : convertIdIntoGid(\n typeof id === 'number' ? BigInt(id) : id,\n 'Fulfillment',\n )\n\n const variables: FulfillmentByIdQueryVariables = { id: gid }\n\n const response = await fetchShopifyGraphql<FulfillmentByIdQuery>({\n query: queryFulfillmentById,\n variables,\n })\n\n if (!response.fulfillment) {\n logger.debug(`No fulfillment found with ID: ${id}`)\n return undefined\n }\n\n return response.fulfillment\n}\n","import { gql } from '../../utils/logger'\n\nexport const queryFulfillmentOrdersByOrderId = gql`#graphql\n query fulfillmentOrdersByOrderId($orderId: ID!) {\n order(id: $orderId) {\n fulfillmentOrders(first: 50) {\n edges {\n node {\n id\n status\n lineItems(first: 100) {\n edges {\n node {\n id\n remainingQuantity\n totalQuantity\n lineItem {\n id\n }\n }\n }\n }\n }\n }\n }\n }\n }\n`\n","import type {\n FulfillmentOrdersByOrderIdQuery,\n FulfillmentOrdersByOrderIdQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { logger } from '../../utils/logger.js'\nimport {\n convertIdIntoGid,\n fetchShopifyGraphql,\n} from '../../utils/shopifyFetch.js'\nimport { queryFulfillmentOrdersByOrderId } from './getFulfillmentOrdersByOrderId.queries.js'\n\n// FulfillmentOrder type - derived from the generated GraphQL types\ntype FulfillmentOrderEdge = NonNullable<\n FulfillmentOrdersByOrderIdQuery['order']\n>['fulfillmentOrders']['edges'][number]\n\nexport type FulfillmentOrder = FulfillmentOrderEdge['node']\n\n/**\n * Retrieves all fulfillment orders for a given Shopify order.\n * Returns an empty array if no order is found or if the order has no fulfillment orders.\n *\n * @param {string | number | bigint} orderId - The Shopify order ID. Can be a GID string (e.g., \"gid://shopify/Order/123456789\") or a numeric ID (e.g., 123456789 or 123456789n).\n * @returns {Promise<FulfillmentOrder[]>} A promise that resolves to an array of fulfillment orders.\n * @throws {Error} If the GraphQL query fails or if the response structure is invalid.\n */\nexport async function getFulfillmentOrdersByOrderId(\n orderId: string | number | bigint,\n): Promise<FulfillmentOrder[]> {\n const gid =\n typeof orderId === 'string'\n ? orderId\n : convertIdIntoGid(\n typeof orderId === 'number' ? BigInt(orderId) : orderId,\n 'Order',\n )\n\n const variables: FulfillmentOrdersByOrderIdQueryVariables = { orderId: gid }\n\n const response = await fetchShopifyGraphql<FulfillmentOrdersByOrderIdQuery>({\n query: queryFulfillmentOrdersByOrderId,\n variables,\n })\n\n if (!response.order) {\n logger.debug(`No order found with ID: ${orderId}`)\n return []\n }\n\n return response.order.fulfillmentOrders.edges.map((edge) => edge.node)\n}\n","import { gql } from '../../utils/logger'\n\nexport const queryCustomersByEmail = gql`#graphql\n query customersByEmail($query: String!, $first: Int!) {\n customers(first: $first, query: $query) {\n edges {\n node {\n id\n email\n firstName\n lastName\n numberOfOrders\n amountSpent {\n amount\n currencyCode\n }\n defaultAddress {\n id\n address1\n address2\n city\n province\n country\n zip\n phone\n }\n addresses {\n id\n address1\n address2\n city\n province\n country\n zip\n phone\n }\n }\n }\n }\n }\n`\n","import type {\n CustomersByEmailQuery,\n CustomersByEmailQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { logger } from '../../utils/logger.js'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch.js'\nimport { queryCustomersByEmail } from './getCustomersByEmail.queries.js'\n\n// Customer type - derived from the generated GraphQL types\nexport type Customer =\n CustomersByEmailQuery['customers']['edges'][number]['node']\n\n/**\n * Retrieves customers from Shopify by their email address.\n * Returns an empty array if no customers are found.\n *\n * @param {string} email - The email address to search for.\n * @param {number} limit - Maximum number of customers to return. Defaults to 10.\n * @returns {Promise<Customer[]>} A promise that resolves to an array of customers.\n * @throws {Error} If the GraphQL query fails or if the response structure is invalid.\n */\nexport async function getCustomersByEmail(\n email: string,\n limit = 10,\n): Promise<Customer[]> {\n const variables: CustomersByEmailQueryVariables = {\n query: `email:${email}`,\n first: limit,\n }\n\n const response = await fetchShopifyGraphql<CustomersByEmailQuery>({\n query: queryCustomersByEmail,\n variables,\n })\n\n const customers = response.customers.edges.map((edge) => edge.node)\n\n logger.debug(`Found ${customers.length} customers for email: ${email}`)\n\n return customers\n}\n","import { gql } from '../../utils/logger'\n\nexport const queryCustomerSegmentMembersWithStatistics = gql`#graphql\n query customerSegmentMembersWithStatistics($query: String!, $first: Int!, $statisticsAttributeName: String!) {\n customerSegmentMembers(query: $query, first: $first) {\n statistics {\n attributeStatistics(attributeName: $statisticsAttributeName) {\n sum\n average\n }\n }\n edges {\n node {\n id\n firstName\n lastName\n displayName\n defaultEmailAddress {\n emailAddress\n }\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n totalCount\n }\n }\n`\n","import type {\n CustomerSegmentMembersWithStatisticsQuery,\n CustomerSegmentMembersWithStatisticsQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { logger } from '../../utils/logger.js'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch.js'\nimport { queryCustomerSegmentMembersWithStatistics } from './getCustomerSegmentMembers.queries.js'\n\n// Segment member type - derived from the generated GraphQL types\nexport type CustomerSegmentMember =\n CustomerSegmentMembersWithStatisticsQuery['customerSegmentMembers']['edges'][number]['node']\n\n// Statistics type\nexport type SegmentAttributeStatistics =\n CustomerSegmentMembersWithStatisticsQuery['customerSegmentMembers']['statistics']['attributeStatistics']\n\nexport interface CustomerSegmentMembersResult {\n members: CustomerSegmentMember[]\n totalCount: number\n statistics: {\n attributeStatistics: SegmentAttributeStatistics\n }\n}\n\n/**\n * Retrieves customer segment members from Shopify based on a segment query.\n * Returns members with statistics for the specified attribute.\n *\n * @param {string} query - The segment query filter string (e.g., \"customer_account_status = 'ENABLED'\").\n * @param {string} statisticsAttributeName - Attribute name for statistics (e.g., \"amount_spent\").\n * @param {number} limit - Maximum number of members to return. Defaults to 250.\n * @returns {Promise<CustomerSegmentMembersResult>} Members with statistics.\n * @throws {Error} If the GraphQL query fails.\n */\nexport async function getCustomerSegmentMembers(\n query: string,\n statisticsAttributeName: string,\n limit = 250,\n): Promise<CustomerSegmentMembersResult> {\n const variables: CustomerSegmentMembersWithStatisticsQueryVariables = {\n query,\n first: limit,\n statisticsAttributeName,\n }\n\n const response =\n await fetchShopifyGraphql<CustomerSegmentMembersWithStatisticsQuery>({\n query: queryCustomerSegmentMembersWithStatistics,\n variables,\n })\n\n const members = response.customerSegmentMembers.edges.map((edge) => edge.node)\n\n logger.debug(`Found ${members.length} customer segment members`)\n\n return {\n members,\n totalCount: response.customerSegmentMembers.totalCount,\n statistics: response.customerSegmentMembers.statistics,\n }\n}\n","import { gql } from '../../utils/logger'\n\nexport const queryOrdersByCustomerId = gql`#graphql\n query ordersByCustomerId($customerId: ID!, $first: Int!) {\n customer(id: $customerId) {\n id\n orders(first: $first, reverse: true) {\n edges {\n node {\n id\n name\n createdAt\n cancelledAt\n cancelReason\n displayFulfillmentStatus\n totalPriceSet {\n shopMoney {\n amount\n currencyCode\n }\n }\n lineItems(first: 100) {\n edges {\n node {\n sku\n title\n image {\n url\n width\n height\n altText\n }\n }\n }\n }\n }\n }\n }\n }\n }\n`\n","import type {\n OrdersByCustomerIdQuery,\n OrdersByCustomerIdQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport { logger } from '../../utils/logger.js'\nimport {\n convertIdIntoGid,\n fetchShopifyGraphql,\n} from '../../utils/shopifyFetch.js'\nimport { queryOrdersByCustomerId } from './getOrdersByCustomerId.queries.js'\n\n// OrderPreview type - derived from the generated GraphQL types\ntype CustomerOrders = NonNullable<OrdersByCustomerIdQuery['customer']>['orders']\nexport type OrderPreview = CustomerOrders['edges'][number]['node']\n\n/**\n * Retrieves orders for a specific customer from Shopify.\n * Returns orders sorted by most recent first, or an empty array if customer not found.\n *\n * @param {number | bigint} customerId - The numerical Shopify customer ID.\n * @param {number} limit - Maximum number of orders to return. Defaults to 250.\n * @returns {Promise<OrderPreview[]>} A promise that resolves to an array of order previews.\n * @throws {Error} If the GraphQL query fails.\n */\nexport async function getOrdersByCustomerId(\n customerId: number | bigint,\n limit = 250,\n): Promise<OrderPreview[]> {\n const bigIntId =\n typeof customerId === 'number' ? BigInt(customerId) : customerId\n const gid = convertIdIntoGid(bigIntId, 'Customer')\n\n const variables: OrdersByCustomerIdQueryVariables = {\n customerId: gid,\n first: limit,\n }\n\n const response = await fetchShopifyGraphql<OrdersByCustomerIdQuery>({\n query: queryOrdersByCustomerId,\n variables,\n })\n\n if (!response.customer) {\n logger.debug(`No customer found with ID: ${customerId}`)\n return []\n }\n\n const orders = response.customer.orders.edges.map((edge) => edge.node)\n\n logger.debug(`Got ${orders.length} orders for customer ${customerId}`)\n\n return orders\n}\n","/**\n * Extract numeric ID from a Shopify GID string.\n *\n * @example\n * parseGid('gid://shopify/Order/12345678901234') // → 12345678901234\n * parseGid('gid://shopify/LineItem/999') // → 999\n */\nexport function parseGid(gid: string): number {\n const match = gid.match(/\\d+$/)\n return match ? Number.parseInt(match[0], 10) : 0\n}\n","import { gql } from '../../utils/logger'\n\nexport const queryMetaobjectByHandle = gql`#graphql\n query metaobjectByHandle($handle: MetaobjectHandleInput!) {\n metaobjectByHandle(handle: $handle) {\n id\n handle\n type\n displayName\n updatedAt\n fields {\n key\n value\n type\n }\n }\n }\n`\n","import type {\n MetaobjectByHandleQuery,\n MetaobjectByHandleQueryVariables,\n} from '../../generated-api-types/2025-04/admin.generated.js'\nimport type { MetaobjectHandleInput } from '../../generated-api-types/2025-04/admin.types.js'\nimport { logger } from '../../utils/logger.js'\nimport { fetchShopifyGraphql } from '../../utils/shopifyFetch.js'\nimport { queryMetaobjectByHandle } from './getMetaobjectByHandle.queries.js'\n\n// Metaobject type - derived from the generated GraphQL types\nexport type Metaobject = NonNullable<\n MetaobjectByHandleQuery['metaobjectByHandle']\n>\n\n/**\n * Retrieves a metaobject from Shopify by its handle.\n * Returns undefined if no metaobject is found with the specified type and handle.\n *\n * @param handle - The handle input containing type and handle\n * @returns A promise that resolves to the metaobject data or undefined if not found.\n */\nexport async function getMetaobjectByHandle(\n handle: MetaobjectHandleInput,\n): Promise<Metaobject | undefined> {\n const variables: MetaobjectByHandleQueryVariables = { handle }\n\n const response = await fetchShopifyGraphql<MetaobjectByHandleQuery>({\n query: queryMetaobjectByHandle,\n variables,\n })\n\n if (!response.metaobjectByHandle) {\n logger.debug(\n `No metaobject found with type \"${handle.type}\" and handle \"${handle.handle}\"`,\n )\n return undefined\n }\n\n return response.metaobjectByHandle\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAM,EAAE,IAAI,IAAI;AAET,IAAM,MAAM,OAAO;AAE1B,IAAM,YAAY;AAAA,EAChB,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AACT;AAIA,SAAS,YACP,SACA,aACc;AACd,MAAI,eAAe,eAAe,WAAW;AAC3C,WAAO;AAAA,EACT;AAEA,MAAI,YAAY,QAAQ;AACtB,WAAO;AAAA,EACT;AAEA,MAAI,YAAY,cAAc;AAC5B,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEO,IAAM,qBAAqB,YAAY,IAAI,UAAU,IAAI,SAAS;AACzE,IAAM,sBAAsB,UAAU,kBAAkB;AAEjD,IAAM,SAAS;AAAA,EACpB,OAAO,IAAI,SAAoB;AAC7B,QAAI,UAAU,SAAS,qBAAqB;AAE1C,cAAQ,MAAM,GAAG,IAAI;AAAA,IACvB;AAAA,EACF;AAAA,EACA,MAAM,IAAI,SAAoB;AAC5B,QAAI,UAAU,QAAQ,qBAAqB;AAEzC,cAAQ,KAAK,GAAG,IAAI;AAAA,IACtB;AAAA,EACF;AAAA,EACA,MAAM,IAAI,SAAoB;AAC5B,QAA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AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACsBvC,eAAsB,sBACpB,YACA,QAAQ,KACiB;AACzB,QAAM,WACJ,OAAO,eAAe,WAAW,OAAO,UAAU,IAAI;AACxD,QAAM,MAAM,iBAAiB,UAAU,UAAU;AAEjD,QAAM,YAA8C;AAAA,IAClD,YAAY;AAAA,IACZ,OAAO;AAAA,EACT;AAEA,QAAM,WAAW,MAAM,oBAA6C;AAAA,IAClE,OAAO;AAAA,IACP;AAAA,EACF,CAAC;AAED,MAAI,CAAC,SAAS,UAAU;AACtB,WAAO,MAAM,8BAA8B,UAAU,EAAE;AACvD,WAAO,CAAC;AAAA,EACV;AAEA,QAAM,SAAS,SAAS,SAAS,OAAO,MAAM,IAAI,CAAC,SAAS,KAAK,IAAI;AAErE,SAAO,MAAM,OAAO,OAAO,MAAM,wBAAwB,UAAU,EAAE;AAErE,SAAO;AACT;;;AC7CO,SAAS,SAAS,KAAqB;AAC5C,QAAM,QAAQ,IAAI,MAAM,MAAM;AAC9B,SAAO,QAAQ,OAAO,SAAS,MAAM,CAAC,GAAG,EAAE,IAAI;AACjD;;;ACRO,IAAM,0BAA0B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACmBvC,eAAsB,sBACpB,QACiC;AACjC,QAAM,YAA8C,EAAE,OAAO;AAE7D,QAAM,WAAW,MAAM,oBAA6C;AAAA,IAClE,OAAO;AAAA,IACP;AAAA,EACF,CAAC;AAED,MAAI,CAAC,SAAS,oBAAoB;AAChC,WAAO;AAAA,MACL,kCAAkC,OAAO,IAAI,iBAAiB,OAAO,MAAM;AAAA,IAC7E;AACA,WAAO;AAAA,EACT;AAEA,SAAO,SAAS;AAClB;","names":["import_shopify_api","dotenv","env","mutation","mutation","mutation","mutation","mutation","mutation","mutation","toGid","mutation","mutation","import_zod","import_zod","z","z","import_zod","z","import_zod","z","import_zod","z","import_zod","z"]}
|