From 10dc031690e338dd8b0a6fb763f5163c2f851c3d Mon Sep 17 00:00:00 2001 From: Anton Golub Date: Thu, 19 Sep 2024 08:58:45 +0300 Subject: [PATCH] fix: enhance `TemplateStringArray` detection --- src/main/ts/util.ts | 9 ++++++++- src/main/ts/x.ts | 2 +- src/test/ts/util.test.ts | 15 +++++++++++++-- 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/src/main/ts/util.ts b/src/main/ts/util.ts index f93c448..b242883 100644 --- a/src/main/ts/util.ts +++ b/src/main/ts/util.ts @@ -22,7 +22,14 @@ export const makeDeferred = (): { promise: Promise, resolve export const isPromiseLike = (value: any): boolean => typeof value?.then === 'function' -export const isStringLiteral = (pieces: any) => pieces?.every?.((p: any) => typeof p === 'string') +export const isStringLiteral = ( + pieces: any, + ...rest: any[] +): pieces is TemplateStringsArray => + pieces?.length > 0 && + pieces.raw?.length === pieces.length && + Object.isFrozen(pieces) && + rest.length + 1 === pieces.length export const assign = (target: T, ...extras: E[]): T => Object.defineProperties(target, extras.reduce>((m: any, extra) => diff --git a/src/main/ts/x.ts b/src/main/ts/x.ts index 4328397..c8aa41b 100644 --- a/src/main/ts/x.ts +++ b/src/main/ts/x.ts @@ -93,7 +93,7 @@ export const $: TShell = function(this: any, pieces?: any, ...args: any): any { if (pieces === undefined) return applyMixins($, preset) - if (isStringLiteral(pieces)) return ignite(preset, pieces, ...args) + if (isStringLiteral(pieces, ...args)) return ignite(preset, pieces, ...args) return (...args: any) => $.apply(self ? assign(self, pieces) : pieces, args) } diff --git a/src/test/ts/util.test.ts b/src/test/ts/util.test.ts index d71bd4e..94df44d 100644 --- a/src/test/ts/util.test.ts +++ b/src/test/ts/util.test.ts @@ -1,10 +1,21 @@ import * as assert from 'node:assert' -import { describe, it } from 'node:test' -import { assign } from '../../main/ts/util.js' +import {describe, it, test} from 'node:test' +import { assign, isStringLiteral } from '../../main/ts/util.js' describe('util', () => { it('assign()', () => { assert.deepEqual(assign({a: 1}, {b: 2}), {a: 1, b: 2}) assert.deepEqual(assign({a: 1}, {a: undefined}), {a: 1}) }) + + test('isStringLiteral()', () => { + const bar = 'baz' + assert.ok(isStringLiteral``) + assert.ok(isStringLiteral`foo`) + assert.ok(isStringLiteral`foo ${bar}`) + + assert.ok(!isStringLiteral('')) + assert.ok(!isStringLiteral('foo')) + assert.ok(!isStringLiteral(['foo'])) + }) })