@fluid-app/fluid-cli-theme-dev 0.1.244 → 0.1.246

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.mjs CHANGED
@@ -6019,6 +6019,357 @@ function createPullCommand() {
6019
6019
  });
6020
6020
  }
6021
6021
  //#endregion
6022
+ //#region src/theme/cart-code.ts
6023
+ const SDK_GLOBAL = `(?<![\\w$])(?:(?:window|globalThis|self)\\s*\\.\\s*)?(?:FairShareSDK|FluidCommerceSDK)(?![\\w$])`;
6024
+ const CART_METHODS = [
6025
+ "createCart",
6026
+ "addCartItems",
6027
+ "addEnrollmentPack",
6028
+ "setEnrollment"
6029
+ ];
6030
+ const ADD_METHODS = new Set([
6031
+ "addCartItems",
6032
+ "addEnrollmentPack",
6033
+ "setEnrollment"
6034
+ ]);
6035
+ const CUSTOM_DRAWER_DOCS = "https://docs.fluid.app/themes/custom-cart-drawer";
6036
+ /** The declarative button that performs the same operation, where one exists. */
6037
+ const DECLARATIVE_ALTERNATIVE = {
6038
+ createCart: "",
6039
+ addCartItems: ", use a data-fluid-add-to-cart button",
6040
+ addEnrollmentPack: ", use a data-fluid-add-enrollment-pack button",
6041
+ setEnrollment: ""
6042
+ };
6043
+ /**
6044
+ * Anything in this list means the file opens a drawer at click or renders its
6045
+ * own cart from live state, so the shopper already sees the cart. Matched against
6046
+ * the source with comments blanked but strings kept, so the event names count.
6047
+ */
6048
+ const DRAWER_SIGNALS = [
6049
+ /\bcontrol\s*\??\.\s*(?:open|toggle)\s*\(/,
6050
+ /\b(?:openCart|toggleCart)\s*\(/,
6051
+ /\bfluidCart\s*\??\.\s*(?:open|toggle)\s*\(/,
6052
+ /\bFLUID_(?:OPEN|TOGGLE)_CART\b/,
6053
+ /data-fluid-cart\b/,
6054
+ /\bonCartChange\s*\(/,
6055
+ /\bgetPendingCartItems\s*\(/,
6056
+ /\bCART_ITEMS_ADDING\b/
6057
+ ];
6058
+ const REGEX_PRECEDING_KEYWORDS = new Set([
6059
+ "return",
6060
+ "typeof",
6061
+ "instanceof",
6062
+ "in",
6063
+ "of",
6064
+ "new",
6065
+ "delete",
6066
+ "void",
6067
+ "throw",
6068
+ "case",
6069
+ "do",
6070
+ "else",
6071
+ "yield",
6072
+ "await"
6073
+ ]);
6074
+ function blank(chars, from, to) {
6075
+ for (let i = from; i < to; i++) {
6076
+ const ch = chars[i];
6077
+ if (ch !== "\n" && ch !== "\r") chars[i] = " ";
6078
+ }
6079
+ }
6080
+ function isIdentChar(ch) {
6081
+ return ch !== void 0 && /[\w$]/.test(ch);
6082
+ }
6083
+ /**
6084
+ * Blank comments (in both views) and string/template text and regex literals
6085
+ * (in `code` only). Offsets are preserved. Template literal text is blanked but
6086
+ * the code inside `${ ... }` is kept.
6087
+ */
6088
+ function maskJs(source) {
6089
+ const code = source.split("");
6090
+ const text = source.split("");
6091
+ const n = source.length;
6092
+ let depth = 0;
6093
+ const templateExprDepths = [];
6094
+ let lastSignificant = "";
6095
+ let lastWord = "";
6096
+ const scanString = (start, quote) => {
6097
+ let i = start + 1;
6098
+ while (i < n) {
6099
+ const ch = source[i];
6100
+ if (ch === "\\") {
6101
+ i += 2;
6102
+ continue;
6103
+ }
6104
+ if (ch === quote) break;
6105
+ if (ch === "\n") return i;
6106
+ i++;
6107
+ }
6108
+ blank(code, start + 1, i);
6109
+ return Math.min(i + 1, n);
6110
+ };
6111
+ const scanTemplateText = (start) => {
6112
+ let i = start;
6113
+ while (i < n) {
6114
+ const ch = source[i];
6115
+ if (ch === "\\") {
6116
+ i += 2;
6117
+ continue;
6118
+ }
6119
+ if (ch === "`") {
6120
+ blank(code, start, i);
6121
+ return i + 1;
6122
+ }
6123
+ if (ch === "$" && source[i + 1] === "{") {
6124
+ blank(code, start, i);
6125
+ templateExprDepths.push(depth);
6126
+ return i + 2;
6127
+ }
6128
+ i++;
6129
+ }
6130
+ blank(code, start, n);
6131
+ return n;
6132
+ };
6133
+ const scanRegex = (start) => {
6134
+ let i = start + 1;
6135
+ let inClass = false;
6136
+ while (i < n) {
6137
+ const ch = source[i];
6138
+ if (ch === "\\") {
6139
+ i += 2;
6140
+ continue;
6141
+ }
6142
+ if (ch === "\n") return start + 1;
6143
+ if (ch === "[") inClass = true;
6144
+ else if (ch === "]") inClass = false;
6145
+ else if (ch === "/" && !inClass) break;
6146
+ i++;
6147
+ }
6148
+ if (i >= n) return start + 1;
6149
+ blank(code, start + 1, i);
6150
+ return i + 1;
6151
+ };
6152
+ let i = 0;
6153
+ while (i < n) {
6154
+ const ch = source[i];
6155
+ const next = source[i + 1];
6156
+ if (ch === "/" && next === "/") {
6157
+ let end = source.indexOf("\n", i);
6158
+ if (end === -1) end = n;
6159
+ blank(code, i, end);
6160
+ blank(text, i, end);
6161
+ i = end;
6162
+ continue;
6163
+ }
6164
+ if (ch === "/" && next === "*") {
6165
+ let end = source.indexOf("*/", i + 2);
6166
+ end = end === -1 ? n : end + 2;
6167
+ blank(code, i, end);
6168
+ blank(text, i, end);
6169
+ i = end;
6170
+ continue;
6171
+ }
6172
+ if (ch === "\"" || ch === "'") {
6173
+ i = scanString(i, ch);
6174
+ lastSignificant = ch;
6175
+ lastWord = "";
6176
+ continue;
6177
+ }
6178
+ if (ch === "`") {
6179
+ i = scanTemplateText(i + 1);
6180
+ lastSignificant = "`";
6181
+ lastWord = "";
6182
+ continue;
6183
+ }
6184
+ if (ch === "/") {
6185
+ if (lastSignificant === "" || "(,=:[!&|?{};+-*%<>~^".includes(lastSignificant) || isIdentChar(lastSignificant) && REGEX_PRECEDING_KEYWORDS.has(lastWord)) {
6186
+ const after = scanRegex(i);
6187
+ if (after > i + 1) {
6188
+ i = after;
6189
+ lastSignificant = ")";
6190
+ lastWord = "";
6191
+ continue;
6192
+ }
6193
+ }
6194
+ lastSignificant = "/";
6195
+ lastWord = "";
6196
+ i++;
6197
+ continue;
6198
+ }
6199
+ if (ch === "{") depth++;
6200
+ else if (ch === "}") {
6201
+ if (templateExprDepths.at(-1) === depth) {
6202
+ templateExprDepths.pop();
6203
+ i = scanTemplateText(i + 1);
6204
+ lastSignificant = "`";
6205
+ lastWord = "";
6206
+ continue;
6207
+ }
6208
+ depth = Math.max(0, depth - 1);
6209
+ }
6210
+ if (isIdentChar(ch)) {
6211
+ lastWord = isIdentChar(lastSignificant) ? lastWord + ch : ch;
6212
+ lastSignificant = ch;
6213
+ } else if (!/\s/.test(ch)) {
6214
+ lastSignificant = ch;
6215
+ lastWord = "";
6216
+ }
6217
+ i++;
6218
+ }
6219
+ return {
6220
+ code: code.join(""),
6221
+ text: text.join("")
6222
+ };
6223
+ }
6224
+ const TEXT_LIKE_SCRIPT_TYPE = /^(?:module|(?:text|application)\/(?:java|ecma)script)$/i;
6225
+ const ATTRIBUTE_SOURCE = `(?:[^>"']|"[^"]*"|'[^']*')*`;
6226
+ function blankRegion(source, pattern) {
6227
+ const chars = source.split("");
6228
+ for (const match of source.matchAll(pattern)) blank(chars, match.index, match.index + match[0].length);
6229
+ return {
6230
+ source,
6231
+ blanked: chars.join("")
6232
+ };
6233
+ }
6234
+ /**
6235
+ * The JavaScript of a liquid file, masked and laid back at its original
6236
+ * offsets (everything else is blank). Sources: `<script>` bodies that are
6237
+ * JavaScript, `{% javascript %}` blocks, and inline `on*="..."` handlers.
6238
+ * Liquid comments and HTML comments are blanked first.
6239
+ */
6240
+ function extractLiquidJs(content) {
6241
+ let working = blankRegion(content, /\{%-?\s*comment\s*-?%\}[\s\S]*?\{%-?\s*endcomment\s*-?%\}/g).blanked;
6242
+ working = blankRegion(working, /<!--[\s\S]*?-->/g).blanked;
6243
+ const segments = [];
6244
+ const scriptPattern = new RegExp(`<script\\b(${ATTRIBUTE_SOURCE})>([\\s\\S]*?)<\/script\\s*>`, "gi");
6245
+ for (const match of working.matchAll(scriptPattern)) {
6246
+ const attributes = match[1] ?? "";
6247
+ const body = match[2] ?? "";
6248
+ const type = /\btype\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(attributes);
6249
+ const typeValue = type?.[1] ?? type?.[2] ?? type?.[3];
6250
+ if (typeValue !== void 0 && !TEXT_LIKE_SCRIPT_TYPE.test(typeValue)) continue;
6251
+ segments.push({
6252
+ offset: match.index + 7 + attributes.length + 1,
6253
+ source: body
6254
+ });
6255
+ }
6256
+ for (const match of working.matchAll(/(\{%-?\s*javascript\s*-?%\})([\s\S]*?)\{%-?\s*endjavascript\s*-?%\}/g)) segments.push({
6257
+ offset: match.index + (match[1]?.length ?? 0),
6258
+ source: match[2] ?? ""
6259
+ });
6260
+ const outsideScripts = working.split("");
6261
+ for (const { offset, source } of segments) blank(outsideScripts, offset, offset + source.length);
6262
+ const handlerPattern = /\son[a-z]+\s*=\s*(?:"([^"]*)"|'([^']*)')/gi;
6263
+ const outside = outsideScripts.join("");
6264
+ for (const match of outside.matchAll(handlerPattern)) {
6265
+ const value = match[1] ?? match[2] ?? "";
6266
+ const valueStart = match.index + match[0].length - value.length - 1;
6267
+ segments.push({
6268
+ offset: valueStart,
6269
+ source: value
6270
+ });
6271
+ }
6272
+ const code = content.replace(/[^\n\r]/g, " ").split("");
6273
+ const text = code.slice();
6274
+ for (const { offset, source } of segments) {
6275
+ const views = maskJs(source);
6276
+ for (let i = 0; i < source.length; i++) {
6277
+ code[offset + i] = views.code[i];
6278
+ text[offset + i] = views.text[i];
6279
+ }
6280
+ }
6281
+ return {
6282
+ code: code.join(""),
6283
+ text: text.join("")
6284
+ };
6285
+ }
6286
+ function parseBindingList(list) {
6287
+ const pairs = [];
6288
+ for (const part of list.split(",")) {
6289
+ const match = /^\s*([A-Za-z_$][\w$]*)\s*(?:(?::|\bas\b)\s*([A-Za-z_$][\w$]*))?\s*(?:=.*)?$/s.exec(part);
6290
+ if (match) pairs.push([match[1], match[2] ?? match[1]]);
6291
+ }
6292
+ return pairs;
6293
+ }
6294
+ function findBindings(views) {
6295
+ const objects = /* @__PURE__ */ new Set();
6296
+ const functions = /* @__PURE__ */ new Map();
6297
+ const isMethod = (name) => CART_METHODS.includes(name);
6298
+ const aliasPattern = new RegExp(`(?<![\\w$.])(?:(?:const|let|var)\\s+)?([A-Za-z_$][\\w$]*)\\s*=(?!=)\\s*${SDK_GLOBAL}(?=[ \\t]*(?:[;,)\\r\\n]|\\|\\||\\?\\?|$))`, "g");
6299
+ for (const match of views.code.matchAll(aliasPattern)) objects.add(match[1]);
6300
+ const destructurePattern = new RegExp(`(?:const|let|var)\\s*\\{([^}]*)\\}\\s*=\\s*${SDK_GLOBAL}`, "g");
6301
+ for (const match of views.code.matchAll(destructurePattern)) for (const [method, local] of parseBindingList(match[1])) if (isMethod(method)) functions.set(local, method);
6302
+ for (const match of views.text.matchAll(/\bimport\s*\{([^}]*)\}\s*from\s*["']@fluid-app\/(?:fluid|fairshare)["']/g)) for (const [method, local] of parseBindingList(match[1])) if (isMethod(method)) functions.set(local, method);
6303
+ return {
6304
+ objects,
6305
+ functions
6306
+ };
6307
+ }
6308
+ function escapeRegExp(value) {
6309
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6310
+ }
6311
+ function findCartCalls(views) {
6312
+ const { objects, functions } = findBindings(views);
6313
+ const calls = [];
6314
+ const methodAlternation = CART_METHODS.join("|");
6315
+ const receivers = [SDK_GLOBAL, ...[...objects].map((name) => `(?<![\\w$.])${escapeRegExp(name)}(?![\\w$])`)].join("|");
6316
+ const memberCall = new RegExp(`(?:${receivers})\\s*\\??\\.\\s*(${methodAlternation})\\s*\\(`, "g");
6317
+ for (const match of views.code.matchAll(memberCall)) calls.push({
6318
+ method: match[1],
6319
+ index: match.index
6320
+ });
6321
+ for (const [local, method] of functions) {
6322
+ const bareCall = new RegExp(`(?<![\\w$.])(?<!function\\s+)${escapeRegExp(local)}\\s*\\(`, "g");
6323
+ for (const match of views.code.matchAll(bareCall)) calls.push({
6324
+ method,
6325
+ index: match.index
6326
+ });
6327
+ }
6328
+ return calls.sort((a, b) => a.index - b.index);
6329
+ }
6330
+ /** Whether `relativePath` is an `assets/` script that the cart rules scan. */
6331
+ function isCartScannableAsset(relativePath) {
6332
+ return relativePath.startsWith("assets/") && /\.m?js$/.test(relativePath);
6333
+ }
6334
+ function lineAt(content, index) {
6335
+ let line = 1;
6336
+ for (let i = 0; i < index; i++) if (content.charCodeAt(i) === 10) line++;
6337
+ return line;
6338
+ }
6339
+ /**
6340
+ * Scan one theme file (`.liquid`, or an `assets/` `.js`/`.mjs`) and return its
6341
+ * cart-code warnings. Any other file type returns nothing.
6342
+ */
6343
+ function findCartCodeDiagnostics(relativePath, content) {
6344
+ const isLiquid = relativePath.endsWith(".liquid");
6345
+ if (!isLiquid && !isCartScannableAsset(relativePath)) return [];
6346
+ if (!CART_METHODS.some((method) => content.includes(method))) return [];
6347
+ const views = isLiquid ? extractLiquidJs(content) : maskJs(content);
6348
+ const calls = findCartCalls(views);
6349
+ const diagnostics = [];
6350
+ for (const call of calls) {
6351
+ if (call.method !== "createCart") continue;
6352
+ const line = lineAt(content, call.index);
6353
+ diagnostics.push({
6354
+ severity: "warning",
6355
+ rule: "cart/create-cart-for-data",
6356
+ line,
6357
+ message: `${relativePath}:${line}: createCart() always creates a new empty cart and replaces the shopper's stored cart token. Do not call it to read data: use getCountryCode(), getLanguage() or getLocalCart() instead.`
6358
+ });
6359
+ }
6360
+ const firstAdd = calls.find((call) => ADD_METHODS.has(call.method));
6361
+ if (firstAdd && !DRAWER_SIGNALS.some((signal) => signal.test(views.text))) {
6362
+ const line = lineAt(content, firstAdd.index);
6363
+ diagnostics.push({
6364
+ severity: "warning",
6365
+ rule: "cart/custom-add-without-drawer-open",
6366
+ line,
6367
+ message: `${relativePath}:${line}: ${firstAdd.method}() is called here but this file never opens the cart drawer. The SDK drawer does not open for a scripted add, only for declarative buttons. Call FairShareSDK.cart.control.open() at click, before awaiting the add${DECLARATIVE_ALTERNATIVE[firstAdd.method]}, or render your own sidebar from getPendingCartItems() and onCartChange(). See ${CUSTOM_DRAWER_DOCS}.`
6368
+ });
6369
+ }
6370
+ return diagnostics.sort((a, b) => a.line - b.line);
6371
+ }
6372
+ //#endregion
6022
6373
  //#region src/commands/lint.ts
6023
6374
  function sectionNameOf(relativePath) {
6024
6375
  const parts = relativePath.split(/[/\\]/);
@@ -6042,7 +6393,12 @@ function createLintCommand() {
6042
6393
  else console.error(message);
6043
6394
  process.exit(1);
6044
6395
  }
6045
- const liquidFiles = themeRoot.files().filter((f) => f.isLiquid).map((f) => ({
6396
+ const files = themeRoot.files();
6397
+ const liquidFiles = files.filter((f) => f.isLiquid).map((f) => ({
6398
+ file: f,
6399
+ content: f.read()
6400
+ }));
6401
+ const scriptFiles = files.filter((f) => isCartScannableAsset(f.relativePath)).map((f) => ({
6046
6402
  file: f,
6047
6403
  content: f.read()
6048
6404
  }));
@@ -6057,6 +6413,7 @@ function createLintCommand() {
6057
6413
  for (const diagnostic of validateSchemaText(content, { blocksSchemaType })) record(file.relativePath, diagnostic);
6058
6414
  for (const diagnostic of findLiquidBlockTagDiagnostics(content)) record(file.relativePath, diagnostic);
6059
6415
  }
6416
+ for (const { file, content } of [...liquidFiles, ...scriptFiles]) for (const diagnostic of findCartCodeDiagnostics(file.relativePath, content)) record(file.relativePath, diagnostic);
6060
6417
  const existingSectionNames = /* @__PURE__ */ new Set();
6061
6418
  for (const { file } of liquidFiles) {
6062
6419
  const name = sectionNameOf(file.relativePath);
@@ -6082,11 +6439,11 @@ function createLintCommand() {
6082
6439
  ok: errors === 0,
6083
6440
  errors,
6084
6441
  warnings,
6085
- filesChecked: liquidFiles.length,
6442
+ filesChecked: liquidFiles.length + scriptFiles.length,
6086
6443
  ...hasInvalidSettingType ? { validSettingTypes: VALID_SETTING_TYPES } : {},
6087
6444
  files: results
6088
6445
  }));
6089
- else printText(results, errors, warnings, liquidFiles.length);
6446
+ else printText(results, errors, warnings, liquidFiles.length + scriptFiles.length);
6090
6447
  process.exit(errors > 0 ? 1 : 0);
6091
6448
  });
6092
6449
  }