All files / core/blong-gogo/src lib.ts

46.59% Statements 171/367
86.07% Branches 68/79
60.86% Functions 14/23
46.59% Lines 171/367

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 3681x 1x 1x 1x 45097x 45097x 42520x 40678x 1842x 1842x 1842x   42520x 45097x 45097x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 11180x 8477x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x                                                                                 1x           1x 1x 1x 1x 1x 1x 1x           9x 3x 3x 3x 3x 6x 6x 9x 13x 6x 6x 13x 7x 7x 13x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5454x 5454x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3399x 3399x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2696x 2696x 2355x 2355x 2355x 2355x 2355x 2355x 1991x 1991x 1991x 2355x 364x 364x 364x 2355x 2355x                                   825x 825x 825x 825x 800x 800x 877x 13x 13x 864x 864x 800x   1x 1x 5x 5x 5x 5x 5x 5x       5x 1x 1x 10x 10x 10x 10x 10x 10x                     5x                   10x                                                                                                                                                                                                                    
import type {ICallLog, ILog} from '@feasibleone/blong/types';
import ky from 'ky';
 
export function methodId<T>(what: T): T {
    return (
        what &&
        ((typeof what === 'string'
            ? what.replace(/\./g, '').toLowerCase()
            : typeof what === 'object'
              ? Object.fromEntries(
                    Object.entries(what).map(([name, value]) => [methodId(name), value]),
                )
              : what) as T)
    );
}
 
/**
 * Split a handler or template name into its `subject.object.predicate` parts.
 *
 * A capital letter that follows a lower-case one starts a new part — that is how `clusterPodFind`
 * reads as three words — and an `_` or a `-` **joins** the word after it to the one before. The
 * join is what lets a part be several words while the name still reads as three:
 * `clusterPersistent_Volume_ClaimApply` is `cluster.persistent_volume_claim.apply`, and the
 * separator stays in the result, because it is the only record of where the words are. Without it
 * a compound kind had to be written as one lump (`persistentvolumeclaim`), and nothing could tell
 * the lump apart again — the k8s adapter strips the separator and capitalises each word to reach
 * the client's own spelling (`PersistentVolumeClaim`). A name written the other way, with the
 * capitals joined (`clusterPersistentVolumeClaimApply`), is read as four words and lands on a part
 * that names nothing (F-379).
 *
 * Two shapes are inherited and deliberate. Without a `$` only the leading word group is split, so a
 * name may carry a verb phrase in its third part: `partyAclFixtureGet` is `party.acl.fixtureGet`
 * (F-347). A `$`-template splits every word, because its file name is built from the same parts
 * (`$subject$ObjectMerge` is `$subject.$object.merge`) and the `$` stays glued to the word it
 * prefixes (D-044).
 */
export function methodParts(what: string): string {
    if (what.includes('.')) return what;
    // Lower-case the word a separator joins, so it cannot read as a part boundary of its own.
    // The separator itself is kept: it is what says the words belong together.
    const glued = what.replace(
        /([-_])([A-Z])/g,
        (_, separator: string, letter: string) => separator + letter.toLowerCase(),
    );
    if (!glued.includes('$')) {
        // Existing behaviour: split the leading word group only.
        const lowercase = (match: string, word1: string, word2: string, letter: string): string =>
            `${word1}.${word2.toLowerCase()}${letter ? '.' + letter.toLowerCase() : ''}`;
        const capitalWords = /^([^A-Z]+)([A-Z][^A-Z]+)([A-Z])?/;
        return glued.replace(capitalWords, lowercase);
    }
    // `$`-containing template names (e.g. the `$subject`/`$object` placeholders
    // in `core/blong-kopi`): split every camelCase word while keeping `$`
    // glued to the word it prefixes. A `$` followed by an uppercase letter
    // starts a new word, so `$subject$ObjectMerge` → `$subject.$object.merge`
    // (not `$subject$.object.merge`, which would break table/param lookups).
    const words: string[] = [];
    let current = '';
    for (let i = 0; i < glued.length; i++) {
        const ch = glued[i];
        const next = glued[i + 1];
        if (ch === '$') {
            if (current && next && /[A-Z]/.test(next)) {
                words.push(current);
                current = '$';
            } else {
                current += '$';
            }
        } else if (/[A-Z]/.test(ch)) {
            const prev = current[current.length - 1];
            if (current && prev && (prev === '$' || /[A-Z]/.test(prev))) {
                current += ch; // continuation of a `$Word` or an acronym
            } else if (current) {
                words.push(current);
                current = ch;
            } else {
                current = ch;
            }
        } else {
            current += ch;
        }
    }
    if (current) words.push(current);
    return [words[0], ...words.slice(1).map(w => w.toLowerCase())].join('.');
}

export function snakeToCamel(string: string): string {
    return string.replace(/([-_]\w)/g, g => g[1].toUpperCase());
}

export function identifier(string: string): string {
    string = snakeToCamel(string);
    return /[^\w$]/.test(string) ? `'${string}'` : string;
}

export function camelToSentence(str: string): string {
    return str
        .replace(/([a-z])([A-Z])/g, '$1 $2')
        .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
        .toLowerCase();
}
 
export interface IAnnotation {
    name: string;
    params: string[];
}
 
export function parseAnnotatedKey(key: string): {
    annotations: IAnnotation[];
    handlerName: string;
} {
    const tokens = key.trim().split(/\s+/);
    const handlerName = tokens.pop()!;
    if (!handlerName || handlerName.startsWith('@')) {
        throw new Error(
            `Malformed annotated key "${key}": the last token must be a non-empty handler name and must not start with "@".`,
        );
    }
    const annotations: IAnnotation[] = [];
    let current: IAnnotation | null = null;
    for (const token of tokens) {
        if (token.startsWith('@')) {
            current = {name: token.slice(1), params: []};
            annotations.push(current);
        } else if (current) {
            current.params.push(token);
        }
    }
    return {annotations, handlerName};
}
 
/**
 * A port's call channel, when it has one.
 *
 * A port is reachable as `unknown` from the places that want to record a call
 * through it (the handler proxy, the adapter's receipt), because a port is an
 * object the framework attaches handlers to rather than a type it owns. The cast
 * lives here so it stays in one place, and so a port whose logger is a third
 * party's — one without a call channel — simply records nothing instead of
 * throwing on the way through a dispatch.
 */
export function portLogCalls(port: unknown): ICallLog | undefined {
    return (port as {log?: ILog})?.log?.calls;
}
 
/**
 * The name a leg can hold: the wire name the call will actually reach.
 *
 * A handler-group call arrives as a path (`db/accessRoleEnsure`), and its two halves are
 * exactly what a leg is made of - the callee namespace and the method - so a separator
 * becomes a dot; a handler name arrives in camel case (`accessPermissionList`) and the wire
 * name it dispatches under is its dotted form (`access.permission.list`), which is what the
 * declaration has to carry: the callee half of a leg is read as the namespace the call was
 * aimed at, so a handler name there would name a participant that does not exist. Lookups
 * keep the original name: only the declaration is normalised, because the registry knows the
 * path and the leg grammar does not.
 */
export function legName(name: string): string {
    return methodParts(name).replace(/\//g, '.');
}
 
/**
 * Record the call itself, from inside the leg its caller declared.
 *
 * This is the framework's own tracing, not one of the log levels: a handler that
 * calls another method produces one start and one end record for the call, and an
 * error record if it throws. They are written *inside* the leg `declareCall`
 * bound, which is what makes them the call's evidence rather than a participant's,
 * and - because they go through the call channel - they are stored rather than
 * printed unless the process asked for them on stdout. Nothing is assembled at all
 * for a flow that opted out, which is what keeps a high-throughput flow from
 * paying for a picture of itself.
 */
export function recordedCall<T>(port: unknown, leg: string, fn: () => T): T {
    const calls = portLogCalls(port);
    if (!calls?.enabled()) return fn();
    calls.start(leg);
    try {
        const result = fn();
        if (result instanceof Promise) {
            return result.then(
                value => {
                    calls.end(leg);
                    return value;
                },
                error => {
                    calls.error(leg, error);
                    throw error;
                },
            ) as T;
        }
        calls.end(leg);
        return result;
    } catch (error) {
        calls.error(leg, error);
        throw error;
    }
}

/**
 * Returns true when an error type matches the `expect` declaration on `$meta`.
 *
 * Matching rules:
 *  - Exact string: `'foo.bar'` matches only `foo.bar`
 *  - Array of strings: any element that matches (exact or wildcard)
 *  - Wildcard prefix: `'foo.*'` matches any type starting with `foo.`
 */
export function isExpectedError(
    errorType: string | undefined,
    expect: string | string[] | undefined,
): boolean {
    if (!errorType || !expect) return false;
    const patterns = ([] as string[]).concat(expect);
    return patterns.some(pattern => {
        if (pattern.endsWith('.*')) {
            return errorType.startsWith(pattern.slice(0, -1));
        }
        return errorType === pattern;
    });
}

let loginCache: Promise<{protocol: string; hostname: string; port: number}> | null = null;
export async function loginService(
    discovery: (service: string) => Promise<{protocol: string; hostname: string; port: number}>,
): Promise<{protocol: string; hostname: string; port: number}> {
    if (!loginCache) loginCache = discovery('login');
    try {
        return await loginCache;
    } catch (error) {
        loginCache = null;
        throw error;
    }
}
 
export async function requestGet(
    url: string,
    errorHttp: (params: Record<string, unknown>) => unknown,
    errorEmpty: () => unknown,
    headers: Record<string, string | undefined> | undefined,
    protocol: string,
    tls: Record<string, unknown> | undefined,
): Promise<unknown> {
    let response;
    try {
        response = await ky.get(url, {
            ...tls,
            ...(headers && {
                headers: {
                    // Every header the caller named, not only the two forwarded-for ones. Dropping
                    // the rest silently dropped the `authorization` an issuer's discovery is read
                    // with, and the API server answered 401 for a request that presented nothing —
                    // a failure with no trace of the cause it was given (F-494).
                    ...(Object.fromEntries(
                        Object.entries(headers).filter(([, value]) => value !== undefined),
                    ) as Record<string, string>),
                    'x-forwarded-proto': headers['x-forwarded-proto'] || protocol,
                    'x-forwarded-host': headers['x-forwarded-host'] || headers.host,
                },
            }),
            throwHttpErrors: false,
        });
    } catch (error) {
        // Name what could not be fetched. A transport failure reaches the log as `fetch failed`
        // and nothing else, so an unreachable dependency was diagnosed by reading DNS names out of
        // the process the hard way (F-494); the address and the resolver's code belong in the
        // message, where whoever reads the failure is already looking.
        const cause = (error as {cause?: {code?: string; hostname?: string; syscall?: string}})
            ?.cause;
        const detail = cause ? [cause.code, cause.syscall, cause.hostname].filter(Boolean).join(' ') : '';
        throw new Error(
            `could not reach ${url}: ${(error as Error)?.message ?? String(error)}` +
                `${detail ? ` (${detail})` : ''}`,
            {cause: error as Error},
        );
    }

    const responseText = await response.text();
    let body: {[key: string]: unknown} | undefined;
    try {
        body = responseText ? JSON.parse(responseText) : undefined;
    } catch {
        body = undefined;
    }

    if (response.status < 200 || response.status >= 300) {
        throw errorHttp({
            statusCode: response.status,
            statusText: response.statusText,
            statusMessage: response.statusText,
            validation: body?.validation,
            debug: body?.debug,
            params: {
                code: response.status,
            },
            req: {
                url: response.url,
                method: 'GET',
            },
        });
    }

    if (body) return body;
    throw errorEmpty();
}

export async function requestPostForm(
    url: string,
    errorHttp: (params: Record<string, unknown>) => unknown,
    errorEmpty: () => unknown,
    headers: Record<string, string | undefined> | undefined,
    protocol: string,
    tls: Record<string, unknown> | undefined,
    form: Record<string, string | number | boolean | null | undefined> | URLSearchParams,
): Promise<string> {
    const forwardedHeaders = headers && {
        'x-forwarded-proto': headers['x-forwarded-proto'] || protocol,
        'x-forwarded-host': headers['x-forwarded-host'] || headers.host,
    };

    const body =
        form instanceof URLSearchParams
            ? form
            : new URLSearchParams(
                  Object.entries(form).map(([key, value]) => [
                      key,
                      value == null ? '' : String(value),
                  ]),
              );

    const response = await ky.post(url, {
        ...tls,
        headers: {
            ...(forwardedHeaders || {}),
            'content-type': 'application/x-www-form-urlencoded',
        },
        body,
        throwHttpErrors: false,
    });

    const responseText = await response.text();
    let responseJson: {[key: string]: unknown} | undefined;
    try {
        responseJson = responseText ? JSON.parse(responseText) : undefined;
    } catch {
        responseJson = undefined;
    }

    if (response.status < 200 || response.status >= 300) {
        throw errorHttp({
            statusCode: response.status,
            statusText: response.statusText,
            statusMessage: response.statusText,
            validation: responseJson?.validation,
            debug: responseJson?.debug,
            params: {
                code: response.status,
            },
            req: {
                url: response.url,
                method: 'POST',
            },
        });
    }

    if (responseText) return responseText;
    throw errorEmpty();
}