@shopkit/data-layer 1.5.0 → 1.7.0
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/README.md +31 -0
- package/dist/adapters/index.js +27 -1
- package/dist/adapters/index.js.map +1 -1
- package/dist/adapters/index.mjs +27 -1
- package/dist/adapters/index.mjs.map +1 -1
- package/dist/index.d.mts +20 -1
- package/dist/index.d.ts +20 -1
- package/dist/index.js +53 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +52 -2
- package/dist/index.mjs.map +1 -1
- package/dist/models/index.d.mts +15 -4
- package/dist/models/index.d.ts +15 -4
- package/dist/static-params/index.js +7 -0
- package/dist/static-params/index.js.map +1 -1
- package/dist/static-params/index.mjs +7 -0
- package/dist/static-params/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/models/index.d.mts
CHANGED
|
@@ -461,14 +461,25 @@ interface IQueryCollectionsRequest {
|
|
|
461
461
|
* detected here. On a product template the widget comes back empty.
|
|
462
462
|
*/
|
|
463
463
|
useRouteHandle?: boolean;
|
|
464
|
+
/**
|
|
465
|
+
* Collections to fetch, by handle, in this order. Becomes
|
|
466
|
+
* `filter.handle: { $in: handles }` unless the filter already names a handle,
|
|
467
|
+
* and collections come back in this order when no `sort` is given.
|
|
468
|
+
*
|
|
469
|
+
* The visual editor's collection picker writes this key (as it does for
|
|
470
|
+
* `COLLECTION_BY_HANDLES`), so a data source declared with `handles` stays
|
|
471
|
+
* editable by the merchant; one declared with `filter.handle` is fixed.
|
|
472
|
+
* An empty list fetches nothing (`data: []`) rather than every collection.
|
|
473
|
+
*/
|
|
474
|
+
handles?: string[];
|
|
464
475
|
}
|
|
465
476
|
/**
|
|
466
477
|
* Why a queryCollections call failed, in `error.code`.
|
|
467
478
|
*
|
|
468
|
-
* - `QUERY_REJECTED`: the backend refused the query (a 4xx). A
|
|
469
|
-
* bug; retrying will not help. `error.message` names the path
|
|
470
|
-
* - `UPSTREAM_UNAVAILABLE`: no usable answer — network failure, timeout, 5xx,
|
|
471
|
-
* or a 200 that carried no data. Same meaning as `success: false` on
|
|
479
|
+
* - `QUERY_REJECTED`: the backend refused the query (a 4xx other than 429). A
|
|
480
|
+
* template or code bug; retrying will not help. `error.message` names the path.
|
|
481
|
+
* - `UPSTREAM_UNAVAILABLE`: no usable answer — network failure, timeout, 5xx, a
|
|
482
|
+
* gateway 429 (rate limited), or a 200 that carried no data. Same meaning as `success: false` on
|
|
472
483
|
* getProduct / getCollection, so a route can keep its last good page.
|
|
473
484
|
*/
|
|
474
485
|
type QueryCollectionsErrorCode = "QUERY_REJECTED" | "UPSTREAM_UNAVAILABLE";
|
package/dist/models/index.d.ts
CHANGED
|
@@ -461,14 +461,25 @@ interface IQueryCollectionsRequest {
|
|
|
461
461
|
* detected here. On a product template the widget comes back empty.
|
|
462
462
|
*/
|
|
463
463
|
useRouteHandle?: boolean;
|
|
464
|
+
/**
|
|
465
|
+
* Collections to fetch, by handle, in this order. Becomes
|
|
466
|
+
* `filter.handle: { $in: handles }` unless the filter already names a handle,
|
|
467
|
+
* and collections come back in this order when no `sort` is given.
|
|
468
|
+
*
|
|
469
|
+
* The visual editor's collection picker writes this key (as it does for
|
|
470
|
+
* `COLLECTION_BY_HANDLES`), so a data source declared with `handles` stays
|
|
471
|
+
* editable by the merchant; one declared with `filter.handle` is fixed.
|
|
472
|
+
* An empty list fetches nothing (`data: []`) rather than every collection.
|
|
473
|
+
*/
|
|
474
|
+
handles?: string[];
|
|
464
475
|
}
|
|
465
476
|
/**
|
|
466
477
|
* Why a queryCollections call failed, in `error.code`.
|
|
467
478
|
*
|
|
468
|
-
* - `QUERY_REJECTED`: the backend refused the query (a 4xx). A
|
|
469
|
-
* bug; retrying will not help. `error.message` names the path
|
|
470
|
-
* - `UPSTREAM_UNAVAILABLE`: no usable answer — network failure, timeout, 5xx,
|
|
471
|
-
* or a 200 that carried no data. Same meaning as `success: false` on
|
|
479
|
+
* - `QUERY_REJECTED`: the backend refused the query (a 4xx other than 429). A
|
|
480
|
+
* template or code bug; retrying will not help. `error.message` names the path.
|
|
481
|
+
* - `UPSTREAM_UNAVAILABLE`: no usable answer — network failure, timeout, 5xx, a
|
|
482
|
+
* gateway 429 (rate limited), or a 200 that carried no data. Same meaning as `success: false` on
|
|
472
483
|
* getProduct / getCollection, so a route can keep its last good page.
|
|
473
484
|
*/
|
|
474
485
|
type QueryCollectionsErrorCode = "QUERY_REJECTED" | "UPSTREAM_UNAVAILABLE";
|
|
@@ -138,6 +138,9 @@ var logger = createLogger({
|
|
|
138
138
|
|
|
139
139
|
// src/static-params/index.ts
|
|
140
140
|
var log = logger.child({ module: "static-params" });
|
|
141
|
+
function skipBuildStaticParams() {
|
|
142
|
+
return process.env.SKIP_BUILD_STATIC_PARAMS === "true";
|
|
143
|
+
}
|
|
141
144
|
async function withConcurrency(thunks, limit) {
|
|
142
145
|
const results = new Array(thunks.length);
|
|
143
146
|
let next = 0;
|
|
@@ -184,6 +187,7 @@ async function traverseCollectionProducts(client, collectionsLimit, productsPerC
|
|
|
184
187
|
}
|
|
185
188
|
function createCollectionStaticParams(getClient, options) {
|
|
186
189
|
return async function generateStaticParams() {
|
|
190
|
+
if (skipBuildStaticParams()) return [];
|
|
187
191
|
const limit = options?.limit ?? 250;
|
|
188
192
|
try {
|
|
189
193
|
const result = await getClient().getCollections({ first: limit });
|
|
@@ -203,6 +207,7 @@ function createCollectionStaticParams(getClient, options) {
|
|
|
203
207
|
}
|
|
204
208
|
function createProductStaticParams(getClient, options) {
|
|
205
209
|
return async function generateStaticParams() {
|
|
210
|
+
if (skipBuildStaticParams()) return [];
|
|
206
211
|
const limit = options?.limit ?? 250;
|
|
207
212
|
try {
|
|
208
213
|
const result = await getClient().getProducts({ first: limit });
|
|
@@ -222,6 +227,7 @@ function createProductStaticParams(getClient, options) {
|
|
|
222
227
|
}
|
|
223
228
|
function createProductViaCollectionsStaticParams(getClient, options) {
|
|
224
229
|
return async function generateStaticParams() {
|
|
230
|
+
if (skipBuildStaticParams()) return [];
|
|
225
231
|
try {
|
|
226
232
|
const pairs = await traverseCollectionProducts(
|
|
227
233
|
getClient(),
|
|
@@ -243,6 +249,7 @@ function createProductViaCollectionsStaticParams(getClient, options) {
|
|
|
243
249
|
}
|
|
244
250
|
function createCollectionProductStaticParams(getClient, options) {
|
|
245
251
|
return async function generateStaticParams() {
|
|
252
|
+
if (skipBuildStaticParams()) return [];
|
|
246
253
|
try {
|
|
247
254
|
const pairs = await traverseCollectionProducts(
|
|
248
255
|
getClient(),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/logger/index.ts","../../src/static-params/index.ts"],"names":[],"mappings":";;;AA2BA,IAAM,UAAA,GAAa;AAAA,EACjB,KAAA,EAAO,EAAA;AAAA,EACP,KAAA,EAAO,EAAA;AAAA,EACP,IAAA,EAAM,EAAA;AAAA,EACN,IAAA,EAAM,EAAA;AAAA,EACN,KAAA,EAAO,EAAA;AAAA,EACP,KAAA,EAAO;AACT,CAAA;AAKA,IAAM,UAAA,GAAN,MAAM,WAAA,CAA6B;AAAA,EACjC,KAAA,GAAQ;AAAA,EAAC;AAAA,EACT,KAAA,GAAQ;AAAA,EAAC;AAAA,EACT,IAAA,GAAO;AAAA,EAAC;AAAA,EACR,IAAA,GAAO;AAAA,EAAC;AAAA,EACR,KAAA,GAAQ;AAAA,EAAC;AAAA,EACT,KAAA,GAAQ;AAAA,EAAC;AAAA,EACT,KAAA,GAAgB;AACd,IAAA,OAAO,IAAI,WAAA,EAAW;AAAA,EACxB;AACF,CAAA;AAKA,IAAM,eAAA,GAAN,MAAM,gBAAA,CAAkC;AAAA,EAItC,WAAA,CACE,MAAA,EACA,QAAA,GAAgC,EAAC,EACjC;AACA,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,QAAA,GAAW,QAAA;AAAA,EAClB;AAAA,EAEQ,UAAU,KAAA,EAAyC;AACzD,IAAA,OAAO,WAAW,KAAK,CAAA,IA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Ac,MAAO;AAAA,QAC3C,cAAA;AAAA,QACA,MAAA,EAAQ;AAAA,OACV,CAAE,CAAA;AAAA,IACN,SAAS,KAAA,EAAO;AACd,MAAA,GAAA,CAAI,KAAA,CAAM,uDAAA,EAAyD,KAAA,YAAiB,KAAA,GAAQ,KAAA,GAAQ,IAAI,KAAA,CAAM,MAAA,CAAO,KAAK,CAAC,CAAC,CAAA;AAC5H,MAAA,OAAO,EAAC;AAAA,IACV;AAAA,EACF,CAAA;AACF","file":"index.js","sourcesContent":["/**\n * Logger configuration options\n */\nexport interface LoggerConfig {\n level?: \"trace\" | \"debug\" | \"info\" | \"warn\" | \"error\" | \"fatal\";\n enabled?: boolean;\n name?: string;\n prettyPrint?: boolean;\n redact?: string[];\n}\n\n/**\n * Logger interface for consistent logging across data layer adapters\n */\nexport interface Logger {\n trace: (message: string, ...args: any[]) => void;\n debug: (message: string, ...args: any[]) => void;\n info: (message: string, ...args: any[]) => void;\n warn: (message: string, ...args: any[]) => void;\n error: (message: string, error?: Error, ...args: any[]) => void;\n fatal: (message: string, error?: Error, ...args: any[]) => void;\n child: (bindings: Record<string, any>) => Logger;\n}\n\n/**\n * Log levels with numeric values for comparison\n */\nconst LOG_LEVELS = {\n trace: 10,\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n fatal: 60,\n} as const;\n\n/**\n * No-op logger for when logging is disabled\n */\nclass NoOpLogger implements Logger {\n trace() {}\n debug() {}\n info() {}\n warn() {}\n error() {}\n fatal() {}\n child(): Logger {\n return new NoOpLogger();\n }\n}\n\n/**\n * Simple universal logger that works in all environments\n */\nclass UniversalLogger implements Logger {\n private config: Required<LoggerConfig>;\n private bindings: Record<string, any>;\n\n constructor(\n config: Required<LoggerConfig>,\n bindings: Record<string, any> = {}\n ) {\n this.config = config;\n this.bindings = bindings;\n }\n\n private shouldLog(level: keyof typeof LOG_LEVELS): boolean {\n return LOG_LEVELS[level] >= LOG_LEVELS[this.config.level];\n }\n\n private formatMessage(\n level: string,\n message: string,\n args: any[],\n error?: Error\n ): string {\n const timestamp = new Date().toISOString();\n const name = this.config.name;\n\n let logMessage = this.config.prettyPrint\n ? `[${timestamp}] ${level.toUpperCase()} [${name}]: ${message}`\n : JSON.stringify({\n timestamp,\n level,\n name,\n message,\n ...this.bindings,\n ...(args.length > 0 && { args }),\n ...(error && {\n error: { message: error.message, stack: error.stack },\n }),\n });\n\n if (this.config.prettyPrint && args.length > 0) {\n logMessage += ` ${args\n .map((arg) =>\n typeof arg === \"object\" ? JSON.stringify(arg) : String(arg)\n )\n .join(\" \")}`;\n }\n\n if (this.config.prettyPrint && error) {\n logMessage += ` Error: ${error.message}`;\n if (error.stack) {\n logMessage += `\\n${error.stack}`;\n }\n }\n\n return this.redactSensitiveData(logMessage);\n }\n\n private redactSensitiveData(message: string): string {\n let redactedMessage = message;\n for (const field of this.config.redact) {\n const regex = new RegExp(`\"${field}\"\\\\s*:\\\\s*\"[^\"]*\"`, \"gi\");\n redactedMessage = redactedMessage.replace(\n regex,\n `\"${field}\":\"[REDACTED]\"`\n );\n }\n return redactedMessage;\n }\n\n private log(\n level: keyof typeof LOG_LEVELS,\n message: string,\n args: any[],\n error?: Error\n ): void {\n if (!this.shouldLog(level)) return;\n\n const formattedMessage = this.formatMessage(level, message, args, error);\n\n // Use appropriate console method based on level\n switch (level) {\n case \"trace\":\n console.trace(formattedMessage);\n break;\n case \"debug\":\n console.debug(formattedMessage);\n break;\n case \"info\":\n console.info(formattedMessage);\n break;\n case \"warn\":\n console.warn(formattedMessage);\n break;\n case \"error\":\n case \"fatal\":\n console.error(formattedMessage);\n break;\n }\n }\n\n trace(message: string, ...args: any[]): void {\n this.log(\"trace\", message, args);\n }\n\n debug(message: string, ...args: any[]): void {\n this.log(\"debug\", message, args);\n }\n\n info(message: string, ...args: any[]): void {\n this.log(\"info\", message, args);\n }\n\n warn(message: string, ...args: any[]): void {\n this.log(\"warn\", message, args);\n }\n\n error(message: string, error?: Error, ...args: any[]): void {\n this.log(\"error\", message, args, error);\n }\n\n fatal(message: string, error?: Error, ...args: any[]): void {\n this.log(\"fatal\", message, args, error);\n }\n\n child(bindings: Record<string, any>): Logger {\n return new UniversalLogger(this.config, { ...this.bindings, ...bindings });\n }\n}\n\n/**\n * Create a logger instance\n */\nexport function createLogger(config: LoggerConfig = {}): Logger {\n const fullConfig: Required<LoggerConfig> = {\n level: config.level || \"info\",\n enabled: config.enabled !== false,\n name: config.name || \"@shopkit/data-layer\",\n prettyPrint: config.prettyPrint || false,\n redact: config.redact || [\"password\", \"token\", \"apiKey\", \"secret\"],\n };\n\n // Return no-op logger if disabled\n if (!fullConfig.enabled) {\n return new NoOpLogger();\n }\n\n return new UniversalLogger(fullConfig);\n}\n\n/**\n * Default logger instance for data layer\n * Note: This is disabled by default. Enable it by passing config to createCommerceClient\n */\nexport const logger = createLogger({\n enabled: false,\n level: \"info\",\n prettyPrint: false,\n});\n\n/**\n * Create adapter-specific logger\n */\nexport function createAdapterLogger(\n adapterName: string,\n config: LoggerConfig = {}\n): Logger {\n const baseLogger = createLogger(config);\n return baseLogger.child({ adapter: adapterName });\n}\n\n/**\n * Create service-specific logger\n */\nexport function createServiceLogger(\n serviceName: string,\n config: LoggerConfig = {}\n): Logger {\n const baseLogger = createLogger(config);\n return baseLogger.child({ service: serviceName });\n}\n\n/**\n * Create domain-specific logger (e.g., product, cart, customer)\n */\nexport function createDomainLogger(\n domain: string,\n adapter: string,\n config: LoggerConfig = {}\n): Logger {\n const baseLogger = createLogger(config);\n return baseLogger.child({ domain, adapter });\n}\n","import type { ICommerceClient } from \"../core/interface\";\nimport { logger } from \"../logger\";\n\n// Minimal local shapes — IResponse.data is untyped in the interface,\n// so we narrow only what the factories actually read.\ninterface HasHandle {\n handle?: string | null;\n}\n\ninterface CollectionWithProducts extends HasHandle {\n products?: HasHandle[] | null;\n}\n\nconst log = logger.child({ module: \"static-params\" });\n\n/**\n * Runs thunks with at most `limit` executing concurrently.\n * Preserves result order. Safe when thunks.length < limit.\n *\n * This is a zero-dependency worker-pool — avoids the thundering-herd problem\n * that Promise.all causes when firing hundreds of API calls simultaneously.\n */\nasync function withConcurrency<T>(\n thunks: Array<() => Promise<T>>,\n limit: number,\n): Promise<T[]> {\n const results: T[] = new Array(thunks.length);\n let next = 0;\n async function worker() {\n while (next < thunks.length) {\n const i = next++;\n results[i] = await thunks[i]().catch(() => [] as unknown as T);\n }\n }\n await Promise.all(Array.from({ length: Math.min(limit, thunks.length) }, worker));\n return results;\n}\n\n/**\n * Shared traversal: fetches all collections, then products per collection.\n * Returns ALL { collectionname, productHandle } pairs without deduplication —\n * callers apply their own dedup strategy.\n *\n * API call budget: 1 (getCollections) + N_collections (getCollection).\n * Note: productsPerCollection controls how many products each getCollection call\n * returns — it is NOT a multiplier on request count.\n * Concurrency caps how many getCollection calls run simultaneously (default: 10).\n */\nasync function traverseCollectionProducts(\n client: ICommerceClient,\n collectionsLimit: number,\n productsPerCollection: number,\n concurrency: number,\n): Promise<Array<{ collectionname: string; productHandle: string }>> {\n const collectionsResult = await client.getCollections({ first: collectionsLimit });\n const collections: HasHandle[] = Array.isArray(collectionsResult?.data)\n ? (collectionsResult.data as HasHandle[])\n : [];\n\n if (collections.length === 0) return [];\n\n if (collections.length >= collectionsLimit) {\n log.warn(\n \"getCollections hit the collections limit — some collections may be missing from static build; increase options.collectionsLimit if needed\",\n { count: collections.length, limit: collectionsLimit },\n );\n }\n\n const thunks = collections.map((collection) => async () => {\n const collectionname = collection?.handle;\n if (!collectionname) return [];\n try {\n const result = await client.getCollection({\n handle: collectionname,\n productLimit: productsPerCollection,\n });\n const col = result?.data as CollectionWithProducts | null;\n const products: HasHandle[] = Array.isArray(col?.products) ? (col!.products as HasHandle[]) : [];\n return products\n .map((p) => p?.handle)\n .filter((h): h is string => Boolean(h))\n .map((productHandle) => ({ collectionname, productHandle }));\n } catch (err) {\n log.warn(\n \"Skipping collection during static generation — getCollection failed\",\n { collection: collectionname, err: err instanceof Error ? err.message : String(err) },\n );\n return [];\n }\n });\n\n const pairsNested = await withConcurrency(thunks, concurrency);\n return pairsNested.flat();\n}\n\n/**\n * Factory for /collections/[collectionname] and /collections-b/[collectionname].\n * Fetches ALL collection handles from the commerce backend at build time.\n * Returns [] safely when the API is down or returns no data.\n */\nexport function createCollectionStaticParams(\n getClient: () => ICommerceClient,\n options?: { limit?: number },\n) {\n return async function generateStaticParams() {\n const limit = options?.limit ?? 250;\n try {\n const result = await getClient().getCollections({ first: limit });\n\n const collections: HasHandle[] = Array.isArray(result?.data)\n ? (result.data as HasHandle[])\n : [];\n\n if (collections.length >= limit) {\n log.warn(\n \"getCollections returned max limit — some collections may be missing from static build; increase options.limit if needed\",\n { count: collections.length, limit },\n );\n }\n\n return collections\n .map((c) => c?.handle)\n .filter((h): h is string => Boolean(h))\n .map((handle) => ({ collectionname: handle }));\n } catch (error) {\n log.error(\"getCollections failed during static generation\", error instanceof Error ? error : new Error(String(error)));\n return [];\n }\n };\n}\n\n/**\n * Factory for /products/[handle] routes on backends that expose a direct\n * products-list endpoint (e.g. Shopify Storefront API).\n *\n * NOT for the custom REST backend — that backend has no products-list endpoint.\n * Use createProductViaCollectionsStaticParams instead, which traverses collections\n * to discover all product handles.\n *\n * Returns [] safely when the API is down or returns no data.\n */\nexport function createProductStaticParams(\n getClient: () => ICommerceClient,\n options?: { limit?: number },\n) {\n return async function generateStaticParams() {\n const limit = options?.limit ?? 250;\n try {\n const result = await getClient().getProducts({ first: limit });\n\n const products: HasHandle[] = Array.isArray(result?.data)\n ? (result.data as HasHandle[])\n : [];\n\n if (products.length >= limit) {\n log.warn(\n \"getProducts returned max limit — some products may be missing from static build; increase options.limit if needed\",\n { count: products.length, limit },\n );\n }\n\n return products\n .map((p) => p?.handle)\n .filter((h): h is string => Boolean(h))\n .map((handle) => ({ handle }));\n } catch (error) {\n log.error(\"getProducts failed during static generation\", error instanceof Error ? error : new Error(String(error)));\n return [];\n }\n };\n}\n\n/**\n * Factory for flat /products/[handle] routes on backends without a direct products-list\n * endpoint. Traverses all collections to discover product handles and deduplicates by\n * handle — each unique product appears exactly once in the output.\n * Returns [] safely when the API is down or returns no data.\n *\n * Default limits: 250 collections × 100 products per collection.\n * Tune via options if your backend is rate-limited.\n */\nexport function createProductViaCollectionsStaticParams(\n getClient: () => ICommerceClient,\n options?: {\n collectionsLimit?: number;\n productsPerCollection?: number;\n concurrency?: number;\n },\n) {\n return async function generateStaticParams() {\n try {\n const pairs = await traverseCollectionProducts(\n getClient(),\n options?.collectionsLimit ?? 250,\n options?.productsPerCollection ?? 100,\n options?.concurrency ?? 10,\n );\n\n // Deduplicate by product handle — each unique product appears once.\n const seen = new Set<string>();\n return pairs\n .filter(({ productHandle }) => {\n if (seen.has(productHandle)) return false;\n seen.add(productHandle);\n return true;\n })\n .map(({ productHandle }) => ({ handle: productHandle }));\n } catch (error) {\n log.error(\"getProductHandlesViaCollections failed during static generation\", error instanceof Error ? error : new Error(String(error)));\n return [];\n }\n };\n}\n\n/**\n * Factory for nested /collections/[collectionname]/products/[handle] routes.\n * Produces { collectionname, handle }[] pairs — one entry per valid collection+product\n * combination. A product in multiple collections generates a pair for each collection,\n * so every collection-product page is pre-built. Deduplicates by the full pair key\n * (collectionname + handle) to avoid duplicate Next.js static entries.\n * Returns [] safely when the API is down or returns no data.\n *\n * Default limits: 50 collections × 20 products per collection.\n * Tune via options if your store has more collections or products per collection.\n */\nexport function createCollectionProductStaticParams(\n getClient: () => ICommerceClient,\n options?: {\n collectionsLimit?: number;\n productsPerCollection?: number;\n concurrency?: number;\n },\n) {\n return async function generateStaticParams() {\n try {\n const pairs = await traverseCollectionProducts(\n getClient(),\n options?.collectionsLimit ?? 50,\n options?.productsPerCollection ?? 20,\n options?.concurrency ?? 10,\n );\n\n // Deduplicate by the full pair — a product in multiple collections\n // still generates one entry per collection so every nested route is pre-built.\n const seen = new Set<string>();\n return pairs\n .filter(({ collectionname, productHandle }) => {\n const key = `${collectionname}:${productHandle}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n })\n .map(({ collectionname, productHandle }) => ({\n collectionname,\n handle: productHandle,\n }));\n } catch (error) {\n log.error(\"getCollectionProducts failed during static generation\", error instanceof Error ? error : new Error(String(error)));\n return [];\n }\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/logger/index.ts","../../src/static-params/index.ts"],"names":[],"mappings":";;;AA2BA,IAAM,UAAA,GAAa;AAAA,EACjB,KAAA,EAAO,EAAA;AAAA,EACP,KAAA,EAAO,EAAA;AAAA,EACP,IAAA,EAAM,EAAA;AAAA,EACN,IAAA,EAAM,EAAA;AAAA,EACN,KAAA,EAAO,EAAA;AAAA,EACP,KAAA,EAAO;AACT,CAAA;AAKA,IAAM,UAAA,GAAN,MAAM,WAAA,CAA6B;AAAA,EACjC,KAAA,GAAQ;AAAA,EAAC;AAAA,EACT,KAAA,GAAQ;AAAA,EAAC;AAAA,EACT,IAAA,GAAO;AAAA,EAAC;AAAA,EACR,IAAA,GAAO;AAAA,EAAC;AAAA,EACR,KAAA,GAAQ;AAAA,EAAC;AAAA,EACT,KAAA,GAAQ;AAAA,EAAC;AAAA,EACT,KAAA,GAAgB;AACd,IAAA,OAAO,IAAI,WAAA,EAAW;AAAA,EACxB;AACF,CAAA;AAKA,IAAM,eAAA,GAAN,MAAM,gBAAA,CAAkC;AAAA,EAItC,WAAA,CACE,MAAA,EACA,QAAA,GAAgC,EAAC,EACjC;AACA,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,QAAA,GAAW,QAAA;AAAA,EAClB;AAAA,EAEQ,UAAU,KAAA,EAAyC;AACzD,IAAA,OAAO,WAAW,KAAK,CAAA,IAAK,UAAA,CAAW,IAAA,CAAK,OAAO,KAAK,CAAA;AAAA,EAC1D;AAAA,EAEQ,aAAA,CACN,KAAA,EACA,OAAA,EACA,IAAA,EACA,KAAA,EACQ;AACR,IAAA,MAAM,SAAA,GAAA,iBAAY,IAAI,IAAA,EAAK,EAAE,WAAA,EAAY;AACzC,IAAA,M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OAAO,IAAA;AAAA,MACT,CAAC,CAAA,CACA,GAAA,CAAI,CAAC,EAAE,cAAA,EAAgB,eAAc,MAAO;AAAA,QAC3C,cAAA;AAAA,QACA,MAAA,EAAQ;AAAA,OACV,CAAE,CAAA;AAAA,IACN,SAAS,KAAA,EAAO;AACd,MAAA,GAAA,CAAI,KAAA,CAAM,uDAAA,EAAyD,KAAA,YAAiB,KAAA,GAAQ,KAAA,GAAQ,IAAI,KAAA,CAAM,MAAA,CAAO,KAAK,CAAC,CAAC,CAAA;AAC5H,MAAA,OAAO,EAAC;AAAA,IACV;AAAA,EACF,CAAA;AACF","file":"index.js","sourcesContent":["/**\n * Logger configuration options\n */\nexport interface LoggerConfig {\n level?: \"trace\" | \"debug\" | \"info\" | \"warn\" | \"error\" | \"fatal\";\n enabled?: boolean;\n name?: string;\n prettyPrint?: boolean;\n redact?: string[];\n}\n\n/**\n * Logger interface for consistent logging across data layer adapters\n */\nexport interface Logger {\n trace: (message: string, ...args: any[]) => void;\n debug: (message: string, ...args: any[]) => void;\n info: (message: string, ...args: any[]) => void;\n warn: (message: string, ...args: any[]) => void;\n error: (message: string, error?: Error, ...args: any[]) => void;\n fatal: (message: string, error?: Error, ...args: any[]) => void;\n child: (bindings: Record<string, any>) => Logger;\n}\n\n/**\n * Log levels with numeric values for comparison\n */\nconst LOG_LEVELS = {\n trace: 10,\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n fatal: 60,\n} as const;\n\n/**\n * No-op logger for when logging is disabled\n */\nclass NoOpLogger implements Logger {\n trace() {}\n debug() {}\n info() {}\n warn() {}\n error() {}\n fatal() {}\n child(): Logger {\n return new NoOpLogger();\n }\n}\n\n/**\n * Simple universal logger that works in all environments\n */\nclass UniversalLogger implements Logger {\n private config: Required<LoggerConfig>;\n private bindings: Record<string, any>;\n\n constructor(\n config: Required<LoggerConfig>,\n bindings: Record<string, any> = {}\n ) {\n this.config = config;\n this.bindings = bindings;\n }\n\n private shouldLog(level: keyof typeof LOG_LEVELS): boolean {\n return LOG_LEVELS[level] >= LOG_LEVELS[this.config.level];\n }\n\n private formatMessage(\n level: string,\n message: string,\n args: any[],\n error?: Error\n ): string {\n const timestamp = new Date().toISOString();\n const name = this.config.name;\n\n let logMessage = this.config.prettyPrint\n ? `[${timestamp}] ${level.toUpperCase()} [${name}]: ${message}`\n : JSON.stringify({\n timestamp,\n level,\n name,\n message,\n ...this.bindings,\n ...(args.length > 0 && { args }),\n ...(error && {\n error: { message: error.message, stack: error.stack },\n }),\n });\n\n if (this.config.prettyPrint && args.length > 0) {\n logMessage += ` ${args\n .map((arg) =>\n typeof arg === \"object\" ? JSON.stringify(arg) : String(arg)\n )\n .join(\" \")}`;\n }\n\n if (this.config.prettyPrint && error) {\n logMessage += ` Error: ${error.message}`;\n if (error.stack) {\n logMessage += `\\n${error.stack}`;\n }\n }\n\n return this.redactSensitiveData(logMessage);\n }\n\n private redactSensitiveData(message: string): string {\n let redactedMessage = message;\n for (const field of this.config.redact) {\n const regex = new RegExp(`\"${field}\"\\\\s*:\\\\s*\"[^\"]*\"`, \"gi\");\n redactedMessage = redactedMessage.replace(\n regex,\n `\"${field}\":\"[REDACTED]\"`\n );\n }\n return redactedMessage;\n }\n\n private log(\n level: keyof typeof LOG_LEVELS,\n message: string,\n args: any[],\n error?: Error\n ): void {\n if (!this.shouldLog(level)) return;\n\n const formattedMessage = this.formatMessage(level, message, args, error);\n\n // Use appropriate console method based on level\n switch (level) {\n case \"trace\":\n console.trace(formattedMessage);\n break;\n case \"debug\":\n console.debug(formattedMessage);\n break;\n case \"info\":\n console.info(formattedMessage);\n break;\n case \"warn\":\n console.warn(formattedMessage);\n break;\n case \"error\":\n case \"fatal\":\n console.error(formattedMessage);\n break;\n }\n }\n\n trace(message: string, ...args: any[]): void {\n this.log(\"trace\", message, args);\n }\n\n debug(message: string, ...args: any[]): void {\n this.log(\"debug\", message, args);\n }\n\n info(message: string, ...args: any[]): void {\n this.log(\"info\", message, args);\n }\n\n warn(message: string, ...args: any[]): void {\n this.log(\"warn\", message, args);\n }\n\n error(message: string, error?: Error, ...args: any[]): void {\n this.log(\"error\", message, args, error);\n }\n\n fatal(message: string, error?: Error, ...args: any[]): void {\n this.log(\"fatal\", message, args, error);\n }\n\n child(bindings: Record<string, any>): Logger {\n return new UniversalLogger(this.config, { ...this.bindings, ...bindings });\n }\n}\n\n/**\n * Create a logger instance\n */\nexport function createLogger(config: LoggerConfig = {}): Logger {\n const fullConfig: Required<LoggerConfig> = {\n level: config.level || \"info\",\n enabled: config.enabled !== false,\n name: config.name || \"@shopkit/data-layer\",\n prettyPrint: config.prettyPrint || false,\n redact: config.redact || [\"password\", \"token\", \"apiKey\", \"secret\"],\n };\n\n // Return no-op logger if disabled\n if (!fullConfig.enabled) {\n return new NoOpLogger();\n }\n\n return new UniversalLogger(fullConfig);\n}\n\n/**\n * Default logger instance for data layer\n * Note: This is disabled by default. Enable it by passing config to createCommerceClient\n */\nexport const logger = createLogger({\n enabled: false,\n level: \"info\",\n prettyPrint: false,\n});\n\n/**\n * Create adapter-specific logger\n */\nexport function createAdapterLogger(\n adapterName: string,\n config: LoggerConfig = {}\n): Logger {\n const baseLogger = createLogger(config);\n return baseLogger.child({ adapter: adapterName });\n}\n\n/**\n * Create service-specific logger\n */\nexport function createServiceLogger(\n serviceName: string,\n config: LoggerConfig = {}\n): Logger {\n const baseLogger = createLogger(config);\n return baseLogger.child({ service: serviceName });\n}\n\n/**\n * Create domain-specific logger (e.g., product, cart, customer)\n */\nexport function createDomainLogger(\n domain: string,\n adapter: string,\n config: LoggerConfig = {}\n): Logger {\n const baseLogger = createLogger(config);\n return baseLogger.child({ domain, adapter });\n}\n","import type { ICommerceClient } from \"../core/interface\";\nimport { logger } from \"../logger\";\n\n// Minimal local shapes — IResponse.data is untyped in the interface,\n// so we narrow only what the factories actually read.\ninterface HasHandle {\n handle?: string | null;\n}\n\ninterface CollectionWithProducts extends HasHandle {\n products?: HasHandle[] | null;\n}\n\nconst log = logger.child({ module: \"static-params\" });\n\n/**\n * `SKIP_BUILD_STATIC_PARAMS=true` skips build-time prerendering: every page renders\n * on its first request instead (routes keep `dynamicParams`). For a build host the\n * API gateway rate-limits — a 429 fails a render rather than 404ing it, so\n * prerendering hundreds of pages would fail the whole build.\n */\nfunction skipBuildStaticParams(): boolean {\n return process.env.SKIP_BUILD_STATIC_PARAMS === \"true\";\n}\n\n/**\n * Runs thunks with at most `limit` executing concurrently.\n * Preserves result order. Safe when thunks.length < limit.\n *\n * This is a zero-dependency worker-pool — avoids the thundering-herd problem\n * that Promise.all causes when firing hundreds of API calls simultaneously.\n */\nasync function withConcurrency<T>(\n thunks: Array<() => Promise<T>>,\n limit: number,\n): Promise<T[]> {\n const results: T[] = new Array(thunks.length);\n let next = 0;\n async function worker() {\n while (next < thunks.length) {\n const i = next++;\n results[i] = await thunks[i]().catch(() => [] as unknown as T);\n }\n }\n await Promise.all(Array.from({ length: Math.min(limit, thunks.length) }, worker));\n return results;\n}\n\n/**\n * Shared traversal: fetches all collections, then products per collection.\n * Returns ALL { collectionname, productHandle } pairs without deduplication —\n * callers apply their own dedup strategy.\n *\n * API call budget: 1 (getCollections) + N_collections (getCollection).\n * Note: productsPerCollection controls how many products each getCollection call\n * returns — it is NOT a multiplier on request count.\n * Concurrency caps how many getCollection calls run simultaneously (default: 10).\n */\nasync function traverseCollectionProducts(\n client: ICommerceClient,\n collectionsLimit: number,\n productsPerCollection: number,\n concurrency: number,\n): Promise<Array<{ collectionname: string; productHandle: string }>> {\n const collectionsResult = await client.getCollections({ first: collectionsLimit });\n const collections: HasHandle[] = Array.isArray(collectionsResult?.data)\n ? (collectionsResult.data as HasHandle[])\n : [];\n\n if (collections.length === 0) return [];\n\n if (collections.length >= collectionsLimit) {\n log.warn(\n \"getCollections hit the collections limit — some collections may be missing from static build; increase options.collectionsLimit if needed\",\n { count: collections.length, limit: collectionsLimit },\n );\n }\n\n const thunks = collections.map((collection) => async () => {\n const collectionname = collection?.handle;\n if (!collectionname) return [];\n try {\n const result = await client.getCollection({\n handle: collectionname,\n productLimit: productsPerCollection,\n });\n const col = result?.data as CollectionWithProducts | null;\n const products: HasHandle[] = Array.isArray(col?.products) ? (col!.products as HasHandle[]) : [];\n return products\n .map((p) => p?.handle)\n .filter((h): h is string => Boolean(h))\n .map((productHandle) => ({ collectionname, productHandle }));\n } catch (err) {\n log.warn(\n \"Skipping collection during static generation — getCollection failed\",\n { collection: collectionname, err: err instanceof Error ? err.message : String(err) },\n );\n return [];\n }\n });\n\n const pairsNested = await withConcurrency(thunks, concurrency);\n return pairsNested.flat();\n}\n\n/**\n * Factory for /collections/[collectionname] and /collections-b/[collectionname].\n * Fetches ALL collection handles from the commerce backend at build time.\n * Returns [] safely when the API is down or returns no data.\n */\nexport function createCollectionStaticParams(\n getClient: () => ICommerceClient,\n options?: { limit?: number },\n) {\n return async function generateStaticParams() {\n if (skipBuildStaticParams()) return [];\n const limit = options?.limit ?? 250;\n try {\n const result = await getClient().getCollections({ first: limit });\n\n const collections: HasHandle[] = Array.isArray(result?.data)\n ? (result.data as HasHandle[])\n : [];\n\n if (collections.length >= limit) {\n log.warn(\n \"getCollections returned max limit — some collections may be missing from static build; increase options.limit if needed\",\n { count: collections.length, limit },\n );\n }\n\n return collections\n .map((c) => c?.handle)\n .filter((h): h is string => Boolean(h))\n .map((handle) => ({ collectionname: handle }));\n } catch (error) {\n log.error(\"getCollections failed during static generation\", error instanceof Error ? error : new Error(String(error)));\n return [];\n }\n };\n}\n\n/**\n * Factory for /products/[handle] routes on backends that expose a direct\n * products-list endpoint (e.g. Shopify Storefront API).\n *\n * NOT for the custom REST backend — that backend has no products-list endpoint.\n * Use createProductViaCollectionsStaticParams instead, which traverses collections\n * to discover all product handles.\n *\n * Returns [] safely when the API is down or returns no data.\n */\nexport function createProductStaticParams(\n getClient: () => ICommerceClient,\n options?: { limit?: number },\n) {\n return async function generateStaticParams() {\n if (skipBuildStaticParams()) return [];\n const limit = options?.limit ?? 250;\n try {\n const result = await getClient().getProducts({ first: limit });\n\n const products: HasHandle[] = Array.isArray(result?.data)\n ? (result.data as HasHandle[])\n : [];\n\n if (products.length >= limit) {\n log.warn(\n \"getProducts returned max limit — some products may be missing from static build; increase options.limit if needed\",\n { count: products.length, limit },\n );\n }\n\n return products\n .map((p) => p?.handle)\n .filter((h): h is string => Boolean(h))\n .map((handle) => ({ handle }));\n } catch (error) {\n log.error(\"getProducts failed during static generation\", error instanceof Error ? error : new Error(String(error)));\n return [];\n }\n };\n}\n\n/**\n * Factory for flat /products/[handle] routes on backends without a direct products-list\n * endpoint. Traverses all collections to discover product handles and deduplicates by\n * handle — each unique product appears exactly once in the output.\n * Returns [] safely when the API is down or returns no data.\n *\n * Default limits: 250 collections × 100 products per collection.\n * Tune via options if your backend is rate-limited.\n */\nexport function createProductViaCollectionsStaticParams(\n getClient: () => ICommerceClient,\n options?: {\n collectionsLimit?: number;\n productsPerCollection?: number;\n concurrency?: number;\n },\n) {\n return async function generateStaticParams() {\n if (skipBuildStaticParams()) return [];\n try {\n const pairs = await traverseCollectionProducts(\n getClient(),\n options?.collectionsLimit ?? 250,\n options?.productsPerCollection ?? 100,\n options?.concurrency ?? 10,\n );\n\n // Deduplicate by product handle — each unique product appears once.\n const seen = new Set<string>();\n return pairs\n .filter(({ productHandle }) => {\n if (seen.has(productHandle)) return false;\n seen.add(productHandle);\n return true;\n })\n .map(({ productHandle }) => ({ handle: productHandle }));\n } catch (error) {\n log.error(\"getProductHandlesViaCollections failed during static generation\", error instanceof Error ? error : new Error(String(error)));\n return [];\n }\n };\n}\n\n/**\n * Factory for nested /collections/[collectionname]/products/[handle] routes.\n * Produces { collectionname, handle }[] pairs — one entry per valid collection+product\n * combination. A product in multiple collections generates a pair for each collection,\n * so every collection-product page is pre-built. Deduplicates by the full pair key\n * (collectionname + handle) to avoid duplicate Next.js static entries.\n * Returns [] safely when the API is down or returns no data.\n *\n * Default limits: 50 collections × 20 products per collection.\n * Tune via options if your store has more collections or products per collection.\n */\nexport function createCollectionProductStaticParams(\n getClient: () => ICommerceClient,\n options?: {\n collectionsLimit?: number;\n productsPerCollection?: number;\n concurrency?: number;\n },\n) {\n return async function generateStaticParams() {\n if (skipBuildStaticParams()) return [];\n try {\n const pairs = await traverseCollectionProducts(\n getClient(),\n options?.collectionsLimit ?? 50,\n options?.productsPerCollection ?? 20,\n options?.concurrency ?? 10,\n );\n\n // Deduplicate by the full pair — a product in multiple collections\n // still generates one entry per collection so every nested route is pre-built.\n const seen = new Set<string>();\n return pairs\n .filter(({ collectionname, productHandle }) => {\n const key = `${collectionname}:${productHandle}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n })\n .map(({ collectionname, productHandle }) => ({\n collectionname,\n handle: productHandle,\n }));\n } catch (error) {\n log.error(\"getCollectionProducts failed during static generation\", error instanceof Error ? error : new Error(String(error)));\n return [];\n }\n };\n}\n"]}
|
|
@@ -136,6 +136,9 @@ var logger = createLogger({
|
|
|
136
136
|
|
|
137
137
|
// src/static-params/index.ts
|
|
138
138
|
var log = logger.child({ module: "static-params" });
|
|
139
|
+
function skipBuildStaticParams() {
|
|
140
|
+
return process.env.SKIP_BUILD_STATIC_PARAMS === "true";
|
|
141
|
+
}
|
|
139
142
|
async function withConcurrency(thunks, limit) {
|
|
140
143
|
const results = new Array(thunks.length);
|
|
141
144
|
let next = 0;
|
|
@@ -182,6 +185,7 @@ async function traverseCollectionProducts(client, collectionsLimit, productsPerC
|
|
|
182
185
|
}
|
|
183
186
|
function createCollectionStaticParams(getClient, options) {
|
|
184
187
|
return async function generateStaticParams() {
|
|
188
|
+
if (skipBuildStaticParams()) return [];
|
|
185
189
|
const limit = options?.limit ?? 250;
|
|
186
190
|
try {
|
|
187
191
|
const result = await getClient().getCollections({ first: limit });
|
|
@@ -201,6 +205,7 @@ function createCollectionStaticParams(getClient, options) {
|
|
|
201
205
|
}
|
|
202
206
|
function createProductStaticParams(getClient, options) {
|
|
203
207
|
return async function generateStaticParams() {
|
|
208
|
+
if (skipBuildStaticParams()) return [];
|
|
204
209
|
const limit = options?.limit ?? 250;
|
|
205
210
|
try {
|
|
206
211
|
const result = await getClient().getProducts({ first: limit });
|
|
@@ -220,6 +225,7 @@ function createProductStaticParams(getClient, options) {
|
|
|
220
225
|
}
|
|
221
226
|
function createProductViaCollectionsStaticParams(getClient, options) {
|
|
222
227
|
return async function generateStaticParams() {
|
|
228
|
+
if (skipBuildStaticParams()) return [];
|
|
223
229
|
try {
|
|
224
230
|
const pairs = await traverseCollectionProducts(
|
|
225
231
|
getClient(),
|
|
@@ -241,6 +247,7 @@ function createProductViaCollectionsStaticParams(getClient, options) {
|
|
|
241
247
|
}
|
|
242
248
|
function createCollectionProductStaticParams(getClient, options) {
|
|
243
249
|
return async function generateStaticParams() {
|
|
250
|
+
if (skipBuildStaticParams()) return [];
|
|
244
251
|
try {
|
|
245
252
|
const pairs = await traverseCollectionProducts(
|
|
246
253
|
getClient(),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/logger/index.ts","../../src/static-params/index.ts"],"names":[],"mappings":";AA2BA,IAAM,UAAA,GAAa;AAAA,EACjB,KAAA,EAAO,EAAA;AAAA,EACP,KAAA,EAAO,EAAA;AAAA,EACP,IAAA,EAAM,EAAA;AAAA,EACN,IAAA,EAAM,EAAA;AAAA,EACN,KAAA,EAAO,EAAA;AAAA,EACP,KAAA,EAAO;AACT,CAAA;AAKA,IAAM,UAAA,GAAN,MAAM,WAAA,CAA6B;AAAA,EACjC,KAAA,GAAQ;AAAA,EAAC;AAAA,EACT,KAAA,GAAQ;AAAA,EAAC;AAAA,EACT,IAAA,GAAO;AAAA,EAAC;AAAA,EACR,IAAA,GAAO;AAAA,EAAC;AAAA,EACR,KAAA,GAAQ;AAAA,EAAC;AAAA,EACT,KAAA,GAAQ;AAAA,EAAC;AAAA,EACT,KAAA,GAAgB;AACd,IAAA,OAAO,IAAI,WAAA,EAAW;AAAA,EACxB;AACF,CAAA;AAKA,IAAM,eAAA,GAAN,MAAM,gBAAA,C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AI,aAAa,CAAA,CAAA;AAC9C,QAAA,IAAI,IAAA,CAAK,GAAA,CAAI,GAAG,CAAA,EAAG,OAAO,KAAA;AAC1B,QAAA,IAAA,CAAK,IAAI,GAAG,CAAA;AACZ,QAAA,OAAO,IAAA;AAAA,MACT,CAAC,CAAA,CACA,GAAA,CAAI,CAAC,EAAE,cAAA,EAAgB,eAAc,MAAO;AAAA,QAC3C,cAAA;AAAA,QACA,MAAA,EAAQ;AAAA,OACV,CAAE,CAAA;AAAA,IACN,SAAS,KAAA,EAAO;AACd,MAAA,GAAA,CAAI,KAAA,CAAM,uDAAA,EAAyD,KAAA,YAAiB,KAAA,GAAQ,KAAA,GAAQ,IAAI,KAAA,CAAM,MAAA,CAAO,KAAK,CAAC,CAAC,CAAA;AAC5H,MAAA,OAAO,EAAC;AAAA,IACV;AAAA,EACF,CAAA;AACF","file":"index.mjs","sourcesContent":["/**\n * Logger configuration options\n */\nexport interface LoggerConfig {\n level?: \"trace\" | \"debug\" | \"info\" | \"warn\" | \"error\" | \"fatal\";\n enabled?: boolean;\n name?: string;\n prettyPrint?: boolean;\n redact?: string[];\n}\n\n/**\n * Logger interface for consistent logging across data layer adapters\n */\nexport interface Logger {\n trace: (message: string, ...args: any[]) => void;\n debug: (message: string, ...args: any[]) => void;\n info: (message: string, ...args: any[]) => void;\n warn: (message: string, ...args: any[]) => void;\n error: (message: string, error?: Error, ...args: any[]) => void;\n fatal: (message: string, error?: Error, ...args: any[]) => void;\n child: (bindings: Record<string, any>) => Logger;\n}\n\n/**\n * Log levels with numeric values for comparison\n */\nconst LOG_LEVELS = {\n trace: 10,\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n fatal: 60,\n} as const;\n\n/**\n * No-op logger for when logging is disabled\n */\nclass NoOpLogger implements Logger {\n trace() {}\n debug() {}\n info() {}\n warn() {}\n error() {}\n fatal() {}\n child(): Logger {\n return new NoOpLogger();\n }\n}\n\n/**\n * Simple universal logger that works in all environments\n */\nclass UniversalLogger implements Logger {\n private config: Required<LoggerConfig>;\n private bindings: Record<string, any>;\n\n constructor(\n config: Required<LoggerConfig>,\n bindings: Record<string, any> = {}\n ) {\n this.config = config;\n this.bindings = bindings;\n }\n\n private shouldLog(level: keyof typeof LOG_LEVELS): boolean {\n return LOG_LEVELS[level] >= LOG_LEVELS[this.config.level];\n }\n\n private formatMessage(\n level: string,\n message: string,\n args: any[],\n error?: Error\n ): string {\n const timestamp = new Date().toISOString();\n const name = this.config.name;\n\n let logMessage = this.config.prettyPrint\n ? `[${timestamp}] ${level.toUpperCase()} [${name}]: ${message}`\n : JSON.stringify({\n timestamp,\n level,\n name,\n message,\n ...this.bindings,\n ...(args.length > 0 && { args }),\n ...(error && {\n error: { message: error.message, stack: error.stack },\n }),\n });\n\n if (this.config.prettyPrint && args.length > 0) {\n logMessage += ` ${args\n .map((arg) =>\n typeof arg === \"object\" ? JSON.stringify(arg) : String(arg)\n )\n .join(\" \")}`;\n }\n\n if (this.config.prettyPrint && error) {\n logMessage += ` Error: ${error.message}`;\n if (error.stack) {\n logMessage += `\\n${error.stack}`;\n }\n }\n\n return this.redactSensitiveData(logMessage);\n }\n\n private redactSensitiveData(message: string): string {\n let redactedMessage = message;\n for (const field of this.config.redact) {\n const regex = new RegExp(`\"${field}\"\\\\s*:\\\\s*\"[^\"]*\"`, \"gi\");\n redactedMessage = redactedMessage.replace(\n regex,\n `\"${field}\":\"[REDACTED]\"`\n );\n }\n return redactedMessage;\n }\n\n private log(\n level: keyof typeof LOG_LEVELS,\n message: string,\n args: any[],\n error?: Error\n ): void {\n if (!this.shouldLog(level)) return;\n\n const formattedMessage = this.formatMessage(level, message, args, error);\n\n // Use appropriate console method based on level\n switch (level) {\n case \"trace\":\n console.trace(formattedMessage);\n break;\n case \"debug\":\n console.debug(formattedMessage);\n break;\n case \"info\":\n console.info(formattedMessage);\n break;\n case \"warn\":\n console.warn(formattedMessage);\n break;\n case \"error\":\n case \"fatal\":\n console.error(formattedMessage);\n break;\n }\n }\n\n trace(message: string, ...args: any[]): void {\n this.log(\"trace\", message, args);\n }\n\n debug(message: string, ...args: any[]): void {\n this.log(\"debug\", message, args);\n }\n\n info(message: string, ...args: any[]): void {\n this.log(\"info\", message, args);\n }\n\n warn(message: string, ...args: any[]): void {\n this.log(\"warn\", message, args);\n }\n\n error(message: string, error?: Error, ...args: any[]): void {\n this.log(\"error\", message, args, error);\n }\n\n fatal(message: string, error?: Error, ...args: any[]): void {\n this.log(\"fatal\", message, args, error);\n }\n\n child(bindings: Record<string, any>): Logger {\n return new UniversalLogger(this.config, { ...this.bindings, ...bindings });\n }\n}\n\n/**\n * Create a logger instance\n */\nexport function createLogger(config: LoggerConfig = {}): Logger {\n const fullConfig: Required<LoggerConfig> = {\n level: config.level || \"info\",\n enabled: config.enabled !== false,\n name: config.name || \"@shopkit/data-layer\",\n prettyPrint: config.prettyPrint || false,\n redact: config.redact || [\"password\", \"token\", \"apiKey\", \"secret\"],\n };\n\n // Return no-op logger if disabled\n if (!fullConfig.enabled) {\n return new NoOpLogger();\n }\n\n return new UniversalLogger(fullConfig);\n}\n\n/**\n * Default logger instance for data layer\n * Note: This is disabled by default. Enable it by passing config to createCommerceClient\n */\nexport const logger = createLogger({\n enabled: false,\n level: \"info\",\n prettyPrint: false,\n});\n\n/**\n * Create adapter-specific logger\n */\nexport function createAdapterLogger(\n adapterName: string,\n config: LoggerConfig = {}\n): Logger {\n const baseLogger = createLogger(config);\n return baseLogger.child({ adapter: adapterName });\n}\n\n/**\n * Create service-specific logger\n */\nexport function createServiceLogger(\n serviceName: string,\n config: LoggerConfig = {}\n): Logger {\n const baseLogger = createLogger(config);\n return baseLogger.child({ service: serviceName });\n}\n\n/**\n * Create domain-specific logger (e.g., product, cart, customer)\n */\nexport function createDomainLogger(\n domain: string,\n adapter: string,\n config: LoggerConfig = {}\n): Logger {\n const baseLogger = createLogger(config);\n return baseLogger.child({ domain, adapter });\n}\n","import type { ICommerceClient } from \"../core/interface\";\nimport { logger } from \"../logger\";\n\n// Minimal local shapes — IResponse.data is untyped in the interface,\n// so we narrow only what the factories actually read.\ninterface HasHandle {\n handle?: string | null;\n}\n\ninterface CollectionWithProducts extends HasHandle {\n products?: HasHandle[] | null;\n}\n\nconst log = logger.child({ module: \"static-params\" });\n\n/**\n * Runs thunks with at most `limit` executing concurrently.\n * Preserves result order. Safe when thunks.length < limit.\n *\n * This is a zero-dependency worker-pool — avoids the thundering-herd problem\n * that Promise.all causes when firing hundreds of API calls simultaneously.\n */\nasync function withConcurrency<T>(\n thunks: Array<() => Promise<T>>,\n limit: number,\n): Promise<T[]> {\n const results: T[] = new Array(thunks.length);\n let next = 0;\n async function worker() {\n while (next < thunks.length) {\n const i = next++;\n results[i] = await thunks[i]().catch(() => [] as unknown as T);\n }\n }\n await Promise.all(Array.from({ length: Math.min(limit, thunks.length) }, worker));\n return results;\n}\n\n/**\n * Shared traversal: fetches all collections, then products per collection.\n * Returns ALL { collectionname, productHandle } pairs without deduplication —\n * callers apply their own dedup strategy.\n *\n * API call budget: 1 (getCollections) + N_collections (getCollection).\n * Note: productsPerCollection controls how many products each getCollection call\n * returns — it is NOT a multiplier on request count.\n * Concurrency caps how many getCollection calls run simultaneously (default: 10).\n */\nasync function traverseCollectionProducts(\n client: ICommerceClient,\n collectionsLimit: number,\n productsPerCollection: number,\n concurrency: number,\n): Promise<Array<{ collectionname: string; productHandle: string }>> {\n const collectionsResult = await client.getCollections({ first: collectionsLimit });\n const collections: HasHandle[] = Array.isArray(collectionsResult?.data)\n ? (collectionsResult.data as HasHandle[])\n : [];\n\n if (collections.length === 0) return [];\n\n if (collections.length >= collectionsLimit) {\n log.warn(\n \"getCollections hit the collections limit — some collections may be missing from static build; increase options.collectionsLimit if needed\",\n { count: collections.length, limit: collectionsLimit },\n );\n }\n\n const thunks = collections.map((collection) => async () => {\n const collectionname = collection?.handle;\n if (!collectionname) return [];\n try {\n const result = await client.getCollection({\n handle: collectionname,\n productLimit: productsPerCollection,\n });\n const col = result?.data as CollectionWithProducts | null;\n const products: HasHandle[] = Array.isArray(col?.products) ? (col!.products as HasHandle[]) : [];\n return products\n .map((p) => p?.handle)\n .filter((h): h is string => Boolean(h))\n .map((productHandle) => ({ collectionname, productHandle }));\n } catch (err) {\n log.warn(\n \"Skipping collection during static generation — getCollection failed\",\n { collection: collectionname, err: err instanceof Error ? err.message : String(err) },\n );\n return [];\n }\n });\n\n const pairsNested = await withConcurrency(thunks, concurrency);\n return pairsNested.flat();\n}\n\n/**\n * Factory for /collections/[collectionname] and /collections-b/[collectionname].\n * Fetches ALL collection handles from the commerce backend at build time.\n * Returns [] safely when the API is down or returns no data.\n */\nexport function createCollectionStaticParams(\n getClient: () => ICommerceClient,\n options?: { limit?: number },\n) {\n return async function generateStaticParams() {\n const limit = options?.limit ?? 250;\n try {\n const result = await getClient().getCollections({ first: limit });\n\n const collections: HasHandle[] = Array.isArray(result?.data)\n ? (result.data as HasHandle[])\n : [];\n\n if (collections.length >= limit) {\n log.warn(\n \"getCollections returned max limit — some collections may be missing from static build; increase options.limit if needed\",\n { count: collections.length, limit },\n );\n }\n\n return collections\n .map((c) => c?.handle)\n .filter((h): h is string => Boolean(h))\n .map((handle) => ({ collectionname: handle }));\n } catch (error) {\n log.error(\"getCollections failed during static generation\", error instanceof Error ? error : new Error(String(error)));\n return [];\n }\n };\n}\n\n/**\n * Factory for /products/[handle] routes on backends that expose a direct\n * products-list endpoint (e.g. Shopify Storefront API).\n *\n * NOT for the custom REST backend — that backend has no products-list endpoint.\n * Use createProductViaCollectionsStaticParams instead, which traverses collections\n * to discover all product handles.\n *\n * Returns [] safely when the API is down or returns no data.\n */\nexport function createProductStaticParams(\n getClient: () => ICommerceClient,\n options?: { limit?: number },\n) {\n return async function generateStaticParams() {\n const limit = options?.limit ?? 250;\n try {\n const result = await getClient().getProducts({ first: limit });\n\n const products: HasHandle[] = Array.isArray(result?.data)\n ? (result.data as HasHandle[])\n : [];\n\n if (products.length >= limit) {\n log.warn(\n \"getProducts returned max limit — some products may be missing from static build; increase options.limit if needed\",\n { count: products.length, limit },\n );\n }\n\n return products\n .map((p) => p?.handle)\n .filter((h): h is string => Boolean(h))\n .map((handle) => ({ handle }));\n } catch (error) {\n log.error(\"getProducts failed during static generation\", error instanceof Error ? error : new Error(String(error)));\n return [];\n }\n };\n}\n\n/**\n * Factory for flat /products/[handle] routes on backends without a direct products-list\n * endpoint. Traverses all collections to discover product handles and deduplicates by\n * handle — each unique product appears exactly once in the output.\n * Returns [] safely when the API is down or returns no data.\n *\n * Default limits: 250 collections × 100 products per collection.\n * Tune via options if your backend is rate-limited.\n */\nexport function createProductViaCollectionsStaticParams(\n getClient: () => ICommerceClient,\n options?: {\n collectionsLimit?: number;\n productsPerCollection?: number;\n concurrency?: number;\n },\n) {\n return async function generateStaticParams() {\n try {\n const pairs = await traverseCollectionProducts(\n getClient(),\n options?.collectionsLimit ?? 250,\n options?.productsPerCollection ?? 100,\n options?.concurrency ?? 10,\n );\n\n // Deduplicate by product handle — each unique product appears once.\n const seen = new Set<string>();\n return pairs\n .filter(({ productHandle }) => {\n if (seen.has(productHandle)) return false;\n seen.add(productHandle);\n return true;\n })\n .map(({ productHandle }) => ({ handle: productHandle }));\n } catch (error) {\n log.error(\"getProductHandlesViaCollections failed during static generation\", error instanceof Error ? error : new Error(String(error)));\n return [];\n }\n };\n}\n\n/**\n * Factory for nested /collections/[collectionname]/products/[handle] routes.\n * Produces { collectionname, handle }[] pairs — one entry per valid collection+product\n * combination. A product in multiple collections generates a pair for each collection,\n * so every collection-product page is pre-built. Deduplicates by the full pair key\n * (collectionname + handle) to avoid duplicate Next.js static entries.\n * Returns [] safely when the API is down or returns no data.\n *\n * Default limits: 50 collections × 20 products per collection.\n * Tune via options if your store has more collections or products per collection.\n */\nexport function createCollectionProductStaticParams(\n getClient: () => ICommerceClient,\n options?: {\n collectionsLimit?: number;\n productsPerCollection?: number;\n concurrency?: number;\n },\n) {\n return async function generateStaticParams() {\n try {\n const pairs = await traverseCollectionProducts(\n getClient(),\n options?.collectionsLimit ?? 50,\n options?.productsPerCollection ?? 20,\n options?.concurrency ?? 10,\n );\n\n // Deduplicate by the full pair — a product in multiple collections\n // still generates one entry per collection so every nested route is pre-built.\n const seen = new Set<string>();\n return pairs\n .filter(({ collectionname, productHandle }) => {\n const key = `${collectionname}:${productHandle}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n })\n .map(({ collectionname, productHandle }) => ({\n collectionname,\n handle: productHandle,\n }));\n } catch (error) {\n log.error(\"getCollectionProducts failed during static generation\", error instanceof Error ? error : new Error(String(error)));\n return [];\n }\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/logger/index.ts","../../src/static-params/index.ts"],"names":[],"mappings":";AA2BA,IAAM,UAAA,GAAa;AAAA,EACjB,KAAA,EAAO,EAAA;AAAA,EACP,KAAA,EAAO,EAAA;AAAA,EACP,IAAA,EAAM,EAAA;AAAA,EACN,IAAA,EAAM,EAAA;AAAA,EACN,KAAA,EAAO,EAAA;AAAA,EACP,KAAA,EAAO;AACT,CAAA;AAKA,IAAM,UAAA,GAAN,MAAM,WAAA,CAA6B;AAAA,EACjC,KAAA,GAAQ;AAAA,EAAC;AAAA,EACT,KAAA,GAAQ;AAAA,EAAC;AAAA,EACT,IAAA,GAAO;AAAA,EAAC;AAAA,EACR,IAAA,GAAO;AAAA,EAAC;AAAA,EACR,KAAA,GAAQ;AAAA,EAAC;AAAA,EACT,KAAA,GAAQ;AAAA,EAAC;AAAA,EACT,KAAA,GAAgB;AACd,IAAA,OAAO,IAAI,WAAA,EAAW;AAAA,EACxB;AACF,CAAA;AAKA,IAAM,eAAA,GAAN,MAAM,gBAAA,CAAkC;AAAA,EAItC,WAAA,CACE,MAAA,EACA,QAAA,GAAgC,EAAC,EACjC;AACA,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,QAAA,GAAW,QAAA;AAAA,EAClB;AAAA,EAEQ,UAAU,KAAA,EAAyC;AACzD,IAAA,OAAO,WAA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gB,eAAc,KAAM;AAC7C,QAAA,MAAM,GAAA,GAAM,CAAA,EAAG,cAAc,CAAA,CAAA,EAAI,aAAa,CAAA,CAAA;AAC9C,QAAA,IAAI,IAAA,CAAK,GAAA,CAAI,GAAG,CAAA,EAAG,OAAO,KAAA;AAC1B,QAAA,IAAA,CAAK,IAAI,GAAG,CAAA;AACZ,QAAA,OAAO,IAAA;AAAA,MACT,CAAC,CAAA,CACA,GAAA,CAAI,CAAC,EAAE,cAAA,EAAgB,eAAc,MAAO;AAAA,QAC3C,cAAA;AAAA,QACA,MAAA,EAAQ;AAAA,OACV,CAAE,CAAA;AAAA,IACN,SAAS,KAAA,EAAO;AACd,MAAA,GAAA,CAAI,KAAA,CAAM,uDAAA,EAAyD,KAAA,YAAiB,KAAA,GAAQ,KAAA,GAAQ,IAAI,KAAA,CAAM,MAAA,CAAO,KAAK,CAAC,CAAC,CAAA;AAC5H,MAAA,OAAO,EAAC;AAAA,IACV;AAAA,EACF,CAAA;AACF","file":"index.mjs","sourcesContent":["/**\n * Logger configuration options\n */\nexport interface LoggerConfig {\n level?: \"trace\" | \"debug\" | \"info\" | \"warn\" | \"error\" | \"fatal\";\n enabled?: boolean;\n name?: string;\n prettyPrint?: boolean;\n redact?: string[];\n}\n\n/**\n * Logger interface for consistent logging across data layer adapters\n */\nexport interface Logger {\n trace: (message: string, ...args: any[]) => void;\n debug: (message: string, ...args: any[]) => void;\n info: (message: string, ...args: any[]) => void;\n warn: (message: string, ...args: any[]) => void;\n error: (message: string, error?: Error, ...args: any[]) => void;\n fatal: (message: string, error?: Error, ...args: any[]) => void;\n child: (bindings: Record<string, any>) => Logger;\n}\n\n/**\n * Log levels with numeric values for comparison\n */\nconst LOG_LEVELS = {\n trace: 10,\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n fatal: 60,\n} as const;\n\n/**\n * No-op logger for when logging is disabled\n */\nclass NoOpLogger implements Logger {\n trace() {}\n debug() {}\n info() {}\n warn() {}\n error() {}\n fatal() {}\n child(): Logger {\n return new NoOpLogger();\n }\n}\n\n/**\n * Simple universal logger that works in all environments\n */\nclass UniversalLogger implements Logger {\n private config: Required<LoggerConfig>;\n private bindings: Record<string, any>;\n\n constructor(\n config: Required<LoggerConfig>,\n bindings: Record<string, any> = {}\n ) {\n this.config = config;\n this.bindings = bindings;\n }\n\n private shouldLog(level: keyof typeof LOG_LEVELS): boolean {\n return LOG_LEVELS[level] >= LOG_LEVELS[this.config.level];\n }\n\n private formatMessage(\n level: string,\n message: string,\n args: any[],\n error?: Error\n ): string {\n const timestamp = new Date().toISOString();\n const name = this.config.name;\n\n let logMessage = this.config.prettyPrint\n ? `[${timestamp}] ${level.toUpperCase()} [${name}]: ${message}`\n : JSON.stringify({\n timestamp,\n level,\n name,\n message,\n ...this.bindings,\n ...(args.length > 0 && { args }),\n ...(error && {\n error: { message: error.message, stack: error.stack },\n }),\n });\n\n if (this.config.prettyPrint && args.length > 0) {\n logMessage += ` ${args\n .map((arg) =>\n typeof arg === \"object\" ? JSON.stringify(arg) : String(arg)\n )\n .join(\" \")}`;\n }\n\n if (this.config.prettyPrint && error) {\n logMessage += ` Error: ${error.message}`;\n if (error.stack) {\n logMessage += `\\n${error.stack}`;\n }\n }\n\n return this.redactSensitiveData(logMessage);\n }\n\n private redactSensitiveData(message: string): string {\n let redactedMessage = message;\n for (const field of this.config.redact) {\n const regex = new RegExp(`\"${field}\"\\\\s*:\\\\s*\"[^\"]*\"`, \"gi\");\n redactedMessage = redactedMessage.replace(\n regex,\n `\"${field}\":\"[REDACTED]\"`\n );\n }\n return redactedMessage;\n }\n\n private log(\n level: keyof typeof LOG_LEVELS,\n message: string,\n args: any[],\n error?: Error\n ): void {\n if (!this.shouldLog(level)) return;\n\n const formattedMessage = this.formatMessage(level, message, args, error);\n\n // Use appropriate console method based on level\n switch (level) {\n case \"trace\":\n console.trace(formattedMessage);\n break;\n case \"debug\":\n console.debug(formattedMessage);\n break;\n case \"info\":\n console.info(formattedMessage);\n break;\n case \"warn\":\n console.warn(formattedMessage);\n break;\n case \"error\":\n case \"fatal\":\n console.error(formattedMessage);\n break;\n }\n }\n\n trace(message: string, ...args: any[]): void {\n this.log(\"trace\", message, args);\n }\n\n debug(message: string, ...args: any[]): void {\n this.log(\"debug\", message, args);\n }\n\n info(message: string, ...args: any[]): void {\n this.log(\"info\", message, args);\n }\n\n warn(message: string, ...args: any[]): void {\n this.log(\"warn\", message, args);\n }\n\n error(message: string, error?: Error, ...args: any[]): void {\n this.log(\"error\", message, args, error);\n }\n\n fatal(message: string, error?: Error, ...args: any[]): void {\n this.log(\"fatal\", message, args, error);\n }\n\n child(bindings: Record<string, any>): Logger {\n return new UniversalLogger(this.config, { ...this.bindings, ...bindings });\n }\n}\n\n/**\n * Create a logger instance\n */\nexport function createLogger(config: LoggerConfig = {}): Logger {\n const fullConfig: Required<LoggerConfig> = {\n level: config.level || \"info\",\n enabled: config.enabled !== false,\n name: config.name || \"@shopkit/data-layer\",\n prettyPrint: config.prettyPrint || false,\n redact: config.redact || [\"password\", \"token\", \"apiKey\", \"secret\"],\n };\n\n // Return no-op logger if disabled\n if (!fullConfig.enabled) {\n return new NoOpLogger();\n }\n\n return new UniversalLogger(fullConfig);\n}\n\n/**\n * Default logger instance for data layer\n * Note: This is disabled by default. Enable it by passing config to createCommerceClient\n */\nexport const logger = createLogger({\n enabled: false,\n level: \"info\",\n prettyPrint: false,\n});\n\n/**\n * Create adapter-specific logger\n */\nexport function createAdapterLogger(\n adapterName: string,\n config: LoggerConfig = {}\n): Logger {\n const baseLogger = createLogger(config);\n return baseLogger.child({ adapter: adapterName });\n}\n\n/**\n * Create service-specific logger\n */\nexport function createServiceLogger(\n serviceName: string,\n config: LoggerConfig = {}\n): Logger {\n const baseLogger = createLogger(config);\n return baseLogger.child({ service: serviceName });\n}\n\n/**\n * Create domain-specific logger (e.g., product, cart, customer)\n */\nexport function createDomainLogger(\n domain: string,\n adapter: string,\n config: LoggerConfig = {}\n): Logger {\n const baseLogger = createLogger(config);\n return baseLogger.child({ domain, adapter });\n}\n","import type { ICommerceClient } from \"../core/interface\";\nimport { logger } from \"../logger\";\n\n// Minimal local shapes — IResponse.data is untyped in the interface,\n// so we narrow only what the factories actually read.\ninterface HasHandle {\n handle?: string | null;\n}\n\ninterface CollectionWithProducts extends HasHandle {\n products?: HasHandle[] | null;\n}\n\nconst log = logger.child({ module: \"static-params\" });\n\n/**\n * `SKIP_BUILD_STATIC_PARAMS=true` skips build-time prerendering: every page renders\n * on its first request instead (routes keep `dynamicParams`). For a build host the\n * API gateway rate-limits — a 429 fails a render rather than 404ing it, so\n * prerendering hundreds of pages would fail the whole build.\n */\nfunction skipBuildStaticParams(): boolean {\n return process.env.SKIP_BUILD_STATIC_PARAMS === \"true\";\n}\n\n/**\n * Runs thunks with at most `limit` executing concurrently.\n * Preserves result order. Safe when thunks.length < limit.\n *\n * This is a zero-dependency worker-pool — avoids the thundering-herd problem\n * that Promise.all causes when firing hundreds of API calls simultaneously.\n */\nasync function withConcurrency<T>(\n thunks: Array<() => Promise<T>>,\n limit: number,\n): Promise<T[]> {\n const results: T[] = new Array(thunks.length);\n let next = 0;\n async function worker() {\n while (next < thunks.length) {\n const i = next++;\n results[i] = await thunks[i]().catch(() => [] as unknown as T);\n }\n }\n await Promise.all(Array.from({ length: Math.min(limit, thunks.length) }, worker));\n return results;\n}\n\n/**\n * Shared traversal: fetches all collections, then products per collection.\n * Returns ALL { collectionname, productHandle } pairs without deduplication —\n * callers apply their own dedup strategy.\n *\n * API call budget: 1 (getCollections) + N_collections (getCollection).\n * Note: productsPerCollection controls how many products each getCollection call\n * returns — it is NOT a multiplier on request count.\n * Concurrency caps how many getCollection calls run simultaneously (default: 10).\n */\nasync function traverseCollectionProducts(\n client: ICommerceClient,\n collectionsLimit: number,\n productsPerCollection: number,\n concurrency: number,\n): Promise<Array<{ collectionname: string; productHandle: string }>> {\n const collectionsResult = await client.getCollections({ first: collectionsLimit });\n const collections: HasHandle[] = Array.isArray(collectionsResult?.data)\n ? (collectionsResult.data as HasHandle[])\n : [];\n\n if (collections.length === 0) return [];\n\n if (collections.length >= collectionsLimit) {\n log.warn(\n \"getCollections hit the collections limit — some collections may be missing from static build; increase options.collectionsLimit if needed\",\n { count: collections.length, limit: collectionsLimit },\n );\n }\n\n const thunks = collections.map((collection) => async () => {\n const collectionname = collection?.handle;\n if (!collectionname) return [];\n try {\n const result = await client.getCollection({\n handle: collectionname,\n productLimit: productsPerCollection,\n });\n const col = result?.data as CollectionWithProducts | null;\n const products: HasHandle[] = Array.isArray(col?.products) ? (col!.products as HasHandle[]) : [];\n return products\n .map((p) => p?.handle)\n .filter((h): h is string => Boolean(h))\n .map((productHandle) => ({ collectionname, productHandle }));\n } catch (err) {\n log.warn(\n \"Skipping collection during static generation — getCollection failed\",\n { collection: collectionname, err: err instanceof Error ? err.message : String(err) },\n );\n return [];\n }\n });\n\n const pairsNested = await withConcurrency(thunks, concurrency);\n return pairsNested.flat();\n}\n\n/**\n * Factory for /collections/[collectionname] and /collections-b/[collectionname].\n * Fetches ALL collection handles from the commerce backend at build time.\n * Returns [] safely when the API is down or returns no data.\n */\nexport function createCollectionStaticParams(\n getClient: () => ICommerceClient,\n options?: { limit?: number },\n) {\n return async function generateStaticParams() {\n if (skipBuildStaticParams()) return [];\n const limit = options?.limit ?? 250;\n try {\n const result = await getClient().getCollections({ first: limit });\n\n const collections: HasHandle[] = Array.isArray(result?.data)\n ? (result.data as HasHandle[])\n : [];\n\n if (collections.length >= limit) {\n log.warn(\n \"getCollections returned max limit — some collections may be missing from static build; increase options.limit if needed\",\n { count: collections.length, limit },\n );\n }\n\n return collections\n .map((c) => c?.handle)\n .filter((h): h is string => Boolean(h))\n .map((handle) => ({ collectionname: handle }));\n } catch (error) {\n log.error(\"getCollections failed during static generation\", error instanceof Error ? error : new Error(String(error)));\n return [];\n }\n };\n}\n\n/**\n * Factory for /products/[handle] routes on backends that expose a direct\n * products-list endpoint (e.g. Shopify Storefront API).\n *\n * NOT for the custom REST backend — that backend has no products-list endpoint.\n * Use createProductViaCollectionsStaticParams instead, which traverses collections\n * to discover all product handles.\n *\n * Returns [] safely when the API is down or returns no data.\n */\nexport function createProductStaticParams(\n getClient: () => ICommerceClient,\n options?: { limit?: number },\n) {\n return async function generateStaticParams() {\n if (skipBuildStaticParams()) return [];\n const limit = options?.limit ?? 250;\n try {\n const result = await getClient().getProducts({ first: limit });\n\n const products: HasHandle[] = Array.isArray(result?.data)\n ? (result.data as HasHandle[])\n : [];\n\n if (products.length >= limit) {\n log.warn(\n \"getProducts returned max limit — some products may be missing from static build; increase options.limit if needed\",\n { count: products.length, limit },\n );\n }\n\n return products\n .map((p) => p?.handle)\n .filter((h): h is string => Boolean(h))\n .map((handle) => ({ handle }));\n } catch (error) {\n log.error(\"getProducts failed during static generation\", error instanceof Error ? error : new Error(String(error)));\n return [];\n }\n };\n}\n\n/**\n * Factory for flat /products/[handle] routes on backends without a direct products-list\n * endpoint. Traverses all collections to discover product handles and deduplicates by\n * handle — each unique product appears exactly once in the output.\n * Returns [] safely when the API is down or returns no data.\n *\n * Default limits: 250 collections × 100 products per collection.\n * Tune via options if your backend is rate-limited.\n */\nexport function createProductViaCollectionsStaticParams(\n getClient: () => ICommerceClient,\n options?: {\n collectionsLimit?: number;\n productsPerCollection?: number;\n concurrency?: number;\n },\n) {\n return async function generateStaticParams() {\n if (skipBuildStaticParams()) return [];\n try {\n const pairs = await traverseCollectionProducts(\n getClient(),\n options?.collectionsLimit ?? 250,\n options?.productsPerCollection ?? 100,\n options?.concurrency ?? 10,\n );\n\n // Deduplicate by product handle — each unique product appears once.\n const seen = new Set<string>();\n return pairs\n .filter(({ productHandle }) => {\n if (seen.has(productHandle)) return false;\n seen.add(productHandle);\n return true;\n })\n .map(({ productHandle }) => ({ handle: productHandle }));\n } catch (error) {\n log.error(\"getProductHandlesViaCollections failed during static generation\", error instanceof Error ? error : new Error(String(error)));\n return [];\n }\n };\n}\n\n/**\n * Factory for nested /collections/[collectionname]/products/[handle] routes.\n * Produces { collectionname, handle }[] pairs — one entry per valid collection+product\n * combination. A product in multiple collections generates a pair for each collection,\n * so every collection-product page is pre-built. Deduplicates by the full pair key\n * (collectionname + handle) to avoid duplicate Next.js static entries.\n * Returns [] safely when the API is down or returns no data.\n *\n * Default limits: 50 collections × 20 products per collection.\n * Tune via options if your store has more collections or products per collection.\n */\nexport function createCollectionProductStaticParams(\n getClient: () => ICommerceClient,\n options?: {\n collectionsLimit?: number;\n productsPerCollection?: number;\n concurrency?: number;\n },\n) {\n return async function generateStaticParams() {\n if (skipBuildStaticParams()) return [];\n try {\n const pairs = await traverseCollectionProducts(\n getClient(),\n options?.collectionsLimit ?? 50,\n options?.productsPerCollection ?? 20,\n options?.concurrency ?? 10,\n );\n\n // Deduplicate by the full pair — a product in multiple collections\n // still generates one entry per collection so every nested route is pre-built.\n const seen = new Set<string>();\n return pairs\n .filter(({ collectionname, productHandle }) => {\n const key = `${collectionname}:${productHandle}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n })\n .map(({ collectionname, productHandle }) => ({\n collectionname,\n handle: productHandle,\n }));\n } catch (error) {\n log.error(\"getCollectionProducts failed during static generation\", error instanceof Error ? error : new Error(String(error)));\n return [];\n }\n };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@shopkit/data-layer",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.7.0",
|
|
4
4
|
"description": "Enterprise data abstraction layer providing unified API for e-commerce platforms including Shopify and custom backends",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.mjs",
|