@cogover/sdk 0.18.0 → 0.19.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 +19 -0
- package/dist/compare.d.ts +4 -0
- package/dist/compare.js +67 -0
- package/dist/format.d.ts +22 -0
- package/dist/format.js +135 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +2 -0
- package/docs/en/api-reference/actions.md +1 -1
- package/docs/en/api-reference/formatting.md +88 -0
- package/docs/en/api-reference/overview.md +1 -0
- package/docs/en/usage-guide.md +33 -8
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -711,6 +711,25 @@ Available calls: `org.me`, `org.personnel.get/getMany/managerChain`,
|
|
|
711
711
|
`org.positions.list/get/members`, `org.isInDepartment`, and `org.isManagerOf`.
|
|
712
712
|
Membership `level` is `0` for staff and `1`, `2`, ... for managers, highest first.
|
|
713
713
|
|
|
714
|
+
## Formatting and sorting without `Intl`
|
|
715
|
+
|
|
716
|
+
Runtime V2 has no `Intl`, and `toLocaleString`, `toLocaleDateString`,
|
|
717
|
+
`toLocaleTimeString`, and `localeCompare` ignore their locale there. Use these
|
|
718
|
+
functions instead (0.19.0 and later):
|
|
719
|
+
|
|
720
|
+
```typescript
|
|
721
|
+
import { compareVietnamese, formatDate, formatNumber, formatUsd, formatVnd, sortVietnamese } from "@cogover/sdk";
|
|
722
|
+
|
|
723
|
+
formatNumber(1234567.891); // "1.234.567,891"
|
|
724
|
+
formatUsd(1234.5); // "$1,234.50"
|
|
725
|
+
formatVnd(1234567); // "1.234.567 ₫"
|
|
726
|
+
formatDate(Date.now(), "dd/MM/yyyy HH:mm"); // GMT+7
|
|
727
|
+
names.sort(compareVietnamese);
|
|
728
|
+
```
|
|
729
|
+
|
|
730
|
+
Publishing code that imports them needs a Workspace where Cogover supports SDK
|
|
731
|
+
0.19.0. See `docs/en/api-reference/formatting.md`.
|
|
732
|
+
|
|
714
733
|
## Workspace types
|
|
715
734
|
|
|
716
735
|
`WorkspaceObjects` is an open interface augmented by a generated declaration for
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** Negative, zero or positive: the order a.localeCompare(b, "vi") gave on the previous runtime, for Vietnamese and English text. */
|
|
2
|
+
export declare function compareVietnamese(a: string, b: string): number;
|
|
3
|
+
/** A sorted copy: sortVietnamese(["Bình", "An", "Ân", "Đức", "Dũng"]) returns ["An", "Ân", "Bình", "Dũng", "Đức"]. */
|
|
4
|
+
export declare function sortVietnamese<T>(items: readonly T[], key?: (item: T) => string): T[];
|
package/dist/compare.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// Vietnamese-aware comparison without Intl or localeCompare: letters in Vietnamese alphabet order
|
|
2
|
+
// (a ă â b c d đ e ê ... o ô ơ ... u ư ...), then tone marks, then lower case before upper case.
|
|
3
|
+
const ALPHABET = "a\u0103\u00e2bcd\u0111e\u00eafghijklmno\u00f4\u01a1pqrstu\u01b0vwxyz";
|
|
4
|
+
// A letter followed by one of these marks is another letter of the alphabet (ă, â, ê, ô, ơ, ư).
|
|
5
|
+
const MARKED_LETTERS = {
|
|
6
|
+
"a\u0306": "\u0103", "a\u0302": "\u00e2", "e\u0302": "\u00ea",
|
|
7
|
+
"o\u0302": "\u00f4", "o\u031b": "\u01a1", "u\u031b": "\u01b0",
|
|
8
|
+
};
|
|
9
|
+
// Tone marks, in order: huyền, hỏi, ngã, sắc, nặng.
|
|
10
|
+
const TONES = ["\u0300", "\u0309", "\u0303", "\u0301", "\u0323"];
|
|
11
|
+
// Letters that look like a Vietnamese or English one sort with it (Ð U+00D0 is often typed for Đ but sorts as D).
|
|
12
|
+
const LOOK_ALIKE = { "\u00f0": "d", "\u00f8": "o", "\u0131": "i", "\u0142": "l" };
|
|
13
|
+
function units(text) {
|
|
14
|
+
const result = [];
|
|
15
|
+
const chars = Array.from(text.normalize("NFD"));
|
|
16
|
+
for (let index = 0; index < chars.length; index += 1) {
|
|
17
|
+
const char = chars[index] ?? "";
|
|
18
|
+
const lower = char.toLowerCase();
|
|
19
|
+
let letter = LOOK_ALIKE[lower] ?? lower;
|
|
20
|
+
let tone = letter === lower ? 0 : TONES.length + 1;
|
|
21
|
+
while (index + 1 < chars.length && /\p{M}/u.test(chars[index + 1] ?? "")) {
|
|
22
|
+
const mark = chars[index + 1] ?? "";
|
|
23
|
+
const toneIndex = TONES.indexOf(mark);
|
|
24
|
+
if (toneIndex >= 0)
|
|
25
|
+
tone = toneIndex + 1;
|
|
26
|
+
else
|
|
27
|
+
letter = MARKED_LETTERS[letter + mark] ?? letter;
|
|
28
|
+
index += 1;
|
|
29
|
+
}
|
|
30
|
+
const code = letter.codePointAt(0) ?? 0;
|
|
31
|
+
const position = ALPHABET.indexOf(letter);
|
|
32
|
+
let primary;
|
|
33
|
+
if (position >= 0)
|
|
34
|
+
primary = 3_000_000 + position;
|
|
35
|
+
else if (/\d/.test(letter))
|
|
36
|
+
primary = 2_000_000 + code;
|
|
37
|
+
else if (/\s/u.test(letter))
|
|
38
|
+
primary = code;
|
|
39
|
+
else if (/[\p{P}\p{S}]/u.test(letter))
|
|
40
|
+
primary = 1_000_000 + code;
|
|
41
|
+
else
|
|
42
|
+
primary = 4_000_000 + code;
|
|
43
|
+
result.push({ primary, tone, upper: char !== lower ? 1 : 0 });
|
|
44
|
+
}
|
|
45
|
+
return result;
|
|
46
|
+
}
|
|
47
|
+
function compareLevel(left, right, key) {
|
|
48
|
+
const length = Math.min(left.length, right.length);
|
|
49
|
+
for (let index = 0; index < length; index += 1) {
|
|
50
|
+
const a = left[index]?.[key] ?? 0;
|
|
51
|
+
const b = right[index]?.[key] ?? 0;
|
|
52
|
+
if (a !== b)
|
|
53
|
+
return a < b ? -1 : 1;
|
|
54
|
+
}
|
|
55
|
+
return left.length === right.length ? 0 : left.length < right.length ? -1 : 1;
|
|
56
|
+
}
|
|
57
|
+
/** Negative, zero or positive: the order a.localeCompare(b, "vi") gave on the previous runtime, for Vietnamese and English text. */
|
|
58
|
+
export function compareVietnamese(a, b) {
|
|
59
|
+
const left = units(a);
|
|
60
|
+
const right = units(b);
|
|
61
|
+
return compareLevel(left, right, "primary") || compareLevel(left, right, "tone")
|
|
62
|
+
|| compareLevel(left, right, "upper");
|
|
63
|
+
}
|
|
64
|
+
/** A sorted copy: sortVietnamese(["Bình", "An", "Ân", "Đức", "Dũng"]) returns ["An", "Ân", "Bình", "Dũng", "Đức"]. */
|
|
65
|
+
export function sortVietnamese(items, key = String) {
|
|
66
|
+
return [...items].sort((left, right) => compareVietnamese(key(left), key(right)));
|
|
67
|
+
}
|
package/dist/format.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export type NumberLocale = "vi" | "en";
|
|
2
|
+
/**
|
|
3
|
+
* Formats a number like `toLocaleString` did: grouping every 3 digits, at most `maxDecimals` decimals
|
|
4
|
+
* (trailing zeros removed down to `minDecimals`), rounding half away from zero.
|
|
5
|
+
* formatNumber(1234567.891, "vi") === "1.234.567,891"; formatNumber(1234567.891, "en", 2) === "1,234,567.89"
|
|
6
|
+
* Throws a TypeError when `value` is not a number (a string, null, undefined, a bigint) and a RangeError for another
|
|
7
|
+
* locale than "vi" or "en" or decimals that are not integers from 0 to 20.
|
|
8
|
+
*/
|
|
9
|
+
export declare function formatNumber(value: number, locale?: NumberLocale, maxDecimals?: number, minDecimals?: number): string;
|
|
10
|
+
/** Vietnamese dong, no decimals: formatVnd(1234567) === "1.234.567 \u20ab" (no-break space before the sign). */
|
|
11
|
+
export declare function formatVnd(value: number): string;
|
|
12
|
+
/** US dollars, 2 decimals: formatUsd(1234.5) === "$1,234.50", formatUsd(-3) === "-$3.00". */
|
|
13
|
+
export declare function formatUsd(value: number): string;
|
|
14
|
+
/** Vietnam time (GMT+7, no daylight saving). */
|
|
15
|
+
export declare const VIETNAM_OFFSET_MINUTES: number;
|
|
16
|
+
/**
|
|
17
|
+
* Formats a date in a fixed time zone (default GMT+7). Tokens: yyyy, MM, M, dd, d, HH, H, hh, h, mm, ss, a (AM/PM).
|
|
18
|
+
* Text in single quotes is copied as is. formatDate(Date.UTC(2026, 4, 29, 7, 5, 9), "dd/MM/yyyy HH:mm") === "29/05/2026 14:05"
|
|
19
|
+
* An invalid date gives "Invalid Date". Throws a TypeError when `value` is neither a Date nor a number, and a RangeError
|
|
20
|
+
* for an offset that is not an integer from -1440 to 1440 or a date outside the years 1 to 9999 in that offset.
|
|
21
|
+
*/
|
|
22
|
+
export declare function formatDate(value: Date | number, pattern?: string, offsetMinutes?: number): string;
|
package/dist/format.js
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// Number, currency, date and time formatting without Intl or toLocale* methods.
|
|
2
|
+
const SEPARATORS = {
|
|
3
|
+
vi: { group: ".", decimal: "," },
|
|
4
|
+
en: { group: ",", decimal: "." },
|
|
5
|
+
};
|
|
6
|
+
/** Plain decimal digits of a finite, non-negative number ("1e+21" becomes "1000000000000000000000"). */
|
|
7
|
+
function plainDigits(value) {
|
|
8
|
+
const text = String(value);
|
|
9
|
+
const match = /^(\d+)(?:\.(\d+))?e([+-]\d+)$/.exec(text);
|
|
10
|
+
if (match === null)
|
|
11
|
+
return text;
|
|
12
|
+
const whole = match[1] ?? "";
|
|
13
|
+
const digits = whole + (match[2] ?? "");
|
|
14
|
+
const point = whole.length + Number(match[3]);
|
|
15
|
+
if (point <= 0)
|
|
16
|
+
return "0." + "0".repeat(-point) + digits;
|
|
17
|
+
if (point >= digits.length)
|
|
18
|
+
return digits + "0".repeat(point - digits.length);
|
|
19
|
+
return digits.slice(0, point) + "." + digits.slice(point);
|
|
20
|
+
}
|
|
21
|
+
/** Rounds a plain decimal string to `decimals` digits, half away from zero. Returns [integer, fraction]. */
|
|
22
|
+
function roundDigits(text, decimals) {
|
|
23
|
+
const [integer = "", fraction = ""] = text.split(".");
|
|
24
|
+
if (fraction.length <= decimals)
|
|
25
|
+
return [integer, fraction.padEnd(decimals, "0")];
|
|
26
|
+
const kept = (integer + fraction.slice(0, decimals)).split("").map(Number);
|
|
27
|
+
if (Number(fraction[decimals]) >= 5) {
|
|
28
|
+
let index = kept.length - 1;
|
|
29
|
+
while (index >= 0 && kept[index] === 9) {
|
|
30
|
+
kept[index] = 0;
|
|
31
|
+
index -= 1;
|
|
32
|
+
}
|
|
33
|
+
if (index < 0)
|
|
34
|
+
kept.unshift(1);
|
|
35
|
+
else
|
|
36
|
+
kept[index] = (kept[index] ?? 0) + 1;
|
|
37
|
+
}
|
|
38
|
+
const all = kept.join("");
|
|
39
|
+
const cut = all.length - decimals;
|
|
40
|
+
return [all.slice(0, cut), all.slice(cut)];
|
|
41
|
+
}
|
|
42
|
+
/** The value as a number, or a TypeError: money is never formatted from a string, null or undefined by mistake. */
|
|
43
|
+
function checkNumber(value, name) {
|
|
44
|
+
if (typeof value !== "number") {
|
|
45
|
+
throw new TypeError(name + " expects a number, got " + (value === null ? "null" : typeof value));
|
|
46
|
+
}
|
|
47
|
+
return value;
|
|
48
|
+
}
|
|
49
|
+
/** A number of decimals: an integer from 0 to 20, or a RangeError. */
|
|
50
|
+
function checkDecimals(value, name) {
|
|
51
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > 20) {
|
|
52
|
+
throw new RangeError(name + " must be an integer from 0 to 20");
|
|
53
|
+
}
|
|
54
|
+
return value;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Formats a number like `toLocaleString` did: grouping every 3 digits, at most `maxDecimals` decimals
|
|
58
|
+
* (trailing zeros removed down to `minDecimals`), rounding half away from zero.
|
|
59
|
+
* formatNumber(1234567.891, "vi") === "1.234.567,891"; formatNumber(1234567.891, "en", 2) === "1,234,567.89"
|
|
60
|
+
* Throws a TypeError when `value` is not a number (a string, null, undefined, a bigint) and a RangeError for another
|
|
61
|
+
* locale than "vi" or "en" or decimals that are not integers from 0 to 20.
|
|
62
|
+
*/
|
|
63
|
+
export function formatNumber(value, locale = "vi", maxDecimals = 3, minDecimals = 0) {
|
|
64
|
+
checkNumber(value, "formatNumber");
|
|
65
|
+
if (typeof locale !== "string" || !Object.prototype.hasOwnProperty.call(SEPARATORS, locale)) {
|
|
66
|
+
throw new RangeError("formatNumber supports the locales \"vi\" and \"en\", not " + String(locale));
|
|
67
|
+
}
|
|
68
|
+
checkDecimals(maxDecimals, "maxDecimals");
|
|
69
|
+
checkDecimals(minDecimals, "minDecimals");
|
|
70
|
+
if (minDecimals > maxDecimals)
|
|
71
|
+
throw new RangeError("minDecimals must not be greater than maxDecimals");
|
|
72
|
+
if (Number.isNaN(value))
|
|
73
|
+
return "NaN";
|
|
74
|
+
if (!Number.isFinite(value))
|
|
75
|
+
return value > 0 ? "\u221e" : "-\u221e";
|
|
76
|
+
const { group, decimal } = SEPARATORS[locale];
|
|
77
|
+
let [integer, fraction] = roundDigits(plainDigits(Math.abs(value)), maxDecimals);
|
|
78
|
+
while (fraction.length > minDecimals && fraction.endsWith("0"))
|
|
79
|
+
fraction = fraction.slice(0, -1);
|
|
80
|
+
integer = integer.replace(/^0+(?=\d)/, "");
|
|
81
|
+
const grouped = integer.replace(/\B(?=(\d{3})+(?!\d))/g, group);
|
|
82
|
+
const sign = value < 0 || Object.is(value, -0) ? "-" : "";
|
|
83
|
+
return sign + grouped + (fraction.length > 0 ? decimal + fraction : "");
|
|
84
|
+
}
|
|
85
|
+
/** Vietnamese dong, no decimals: formatVnd(1234567) === "1.234.567 \u20ab" (no-break space before the sign). */
|
|
86
|
+
export function formatVnd(value) {
|
|
87
|
+
return formatNumber(checkNumber(value, "formatVnd"), "vi", 0, 0) + "\u00a0\u20ab";
|
|
88
|
+
}
|
|
89
|
+
/** US dollars, 2 decimals: formatUsd(1234.5) === "$1,234.50", formatUsd(-3) === "-$3.00". */
|
|
90
|
+
export function formatUsd(value) {
|
|
91
|
+
const text = formatNumber(Math.abs(checkNumber(value, "formatUsd")), "en", 2, 2);
|
|
92
|
+
return (value < 0 || Object.is(value, -0) ? "-$" : "$") + text;
|
|
93
|
+
}
|
|
94
|
+
/** Vietnam time (GMT+7, no daylight saving). */
|
|
95
|
+
export const VIETNAM_OFFSET_MINUTES = 7 * 60;
|
|
96
|
+
const pad = (value, length = 2) => String(value).padStart(length, "0");
|
|
97
|
+
/**
|
|
98
|
+
* Formats a date in a fixed time zone (default GMT+7). Tokens: yyyy, MM, M, dd, d, HH, H, hh, h, mm, ss, a (AM/PM).
|
|
99
|
+
* Text in single quotes is copied as is. formatDate(Date.UTC(2026, 4, 29, 7, 5, 9), "dd/MM/yyyy HH:mm") === "29/05/2026 14:05"
|
|
100
|
+
* An invalid date gives "Invalid Date". Throws a TypeError when `value` is neither a Date nor a number, and a RangeError
|
|
101
|
+
* for an offset that is not an integer from -1440 to 1440 or a date outside the years 1 to 9999 in that offset.
|
|
102
|
+
*/
|
|
103
|
+
export function formatDate(value, pattern = "dd/MM/yyyy", offsetMinutes = VIETNAM_OFFSET_MINUTES) {
|
|
104
|
+
if (typeof value !== "number" && !(value instanceof Date)) {
|
|
105
|
+
throw new TypeError("formatDate expects a Date or a number of milliseconds");
|
|
106
|
+
}
|
|
107
|
+
if (typeof pattern !== "string")
|
|
108
|
+
throw new TypeError("formatDate expects the pattern as a string");
|
|
109
|
+
if (typeof offsetMinutes !== "number" || !Number.isInteger(offsetMinutes) || Math.abs(offsetMinutes) > 1440) {
|
|
110
|
+
throw new RangeError("offsetMinutes must be an integer from -1440 to 1440");
|
|
111
|
+
}
|
|
112
|
+
const time = typeof value === "number" ? value : value.getTime();
|
|
113
|
+
if (!Number.isFinite(time))
|
|
114
|
+
return "Invalid Date";
|
|
115
|
+
const shifted = new Date(time + offsetMinutes * 60_000);
|
|
116
|
+
const year = shifted.getUTCFullYear();
|
|
117
|
+
if (!(year >= 1 && year <= 9999))
|
|
118
|
+
throw new RangeError("formatDate supports the years 1 to 9999");
|
|
119
|
+
const hours = shifted.getUTCHours();
|
|
120
|
+
const parts = {
|
|
121
|
+
yyyy: pad(year, 4),
|
|
122
|
+
MM: pad(shifted.getUTCMonth() + 1),
|
|
123
|
+
M: String(shifted.getUTCMonth() + 1),
|
|
124
|
+
dd: pad(shifted.getUTCDate()),
|
|
125
|
+
d: String(shifted.getUTCDate()),
|
|
126
|
+
HH: pad(hours),
|
|
127
|
+
H: String(hours),
|
|
128
|
+
hh: pad(hours % 12 === 0 ? 12 : hours % 12),
|
|
129
|
+
h: String(hours % 12 === 0 ? 12 : hours % 12),
|
|
130
|
+
mm: pad(shifted.getUTCMinutes()),
|
|
131
|
+
ss: pad(shifted.getUTCSeconds()),
|
|
132
|
+
a: hours < 12 ? "AM" : "PM",
|
|
133
|
+
};
|
|
134
|
+
return pattern.replace(/'([^']*)'|yyyy|MM|M|dd|d|HH|H|hh|h|mm|ss|a/g, (token, quoted) => quoted ?? parts[token] ?? token);
|
|
135
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -22,6 +22,9 @@ export type { SecretsApi } from "./secrets.js";
|
|
|
22
22
|
export type { OrgApi, OrgPersonnelApi, OrgDepartmentsApi, OrgPositionsApi, OrgReadOptions, OrgPageOptions, OrgDepartmentMembersOptions, OrgPositionMembersOptions, OrgManagerOptions, OrgPersonnelChainOptions, OrgTreeOptions, OrgIsInDepartmentOptions, OrgIsManagerOfOptions, OrgPersonnelDisplay, OrgNameDisplay, OrgMembership, OrgMember, OrgPersonnel, OrgDepartment, OrgDepartmentNode, OrgPosition, OrgManagerTier, OrgManagerChain, OrgPage, OrgGetManyResult, } from "./org.js";
|
|
23
23
|
export { limits } from "./limits.js";
|
|
24
24
|
export type { LimitsApi, LimitUsage, LimitCounter } from "./limits.js";
|
|
25
|
+
export { formatNumber, formatVnd, formatUsd, formatDate, VIETNAM_OFFSET_MINUTES } from "./format.js";
|
|
26
|
+
export type { NumberLocale } from "./format.js";
|
|
27
|
+
export { compareVietnamese, sortVietnamese } from "./compare.js";
|
|
25
28
|
export { crypto } from "./crypto.js";
|
|
26
29
|
export type { CryptoApi, BinaryEncoding, DecryptOutput, SecretKeyReference, AesKey, AsymmetricKey, AesMode, AesEncryptOptions, AesEncryptResult, AesDecryptOptions, RsaPadding, RsaEncryptOptions, RsaDecryptOptions, SignatureAlgorithm, SignatureOptions, } from "./crypto.js";
|
|
27
30
|
export type { CurrentWorkspace, CurrentWorkspaceMembership, CurrentWorkspaceRole, CurrentUser, UserInvocationContext, SystemInvocationContext, InboundInvocationContext, InvocationContext, } from "./invocation.js";
|
package/dist/index.js
CHANGED
|
@@ -6,6 +6,8 @@ export { defineJob } from "./jobs.js";
|
|
|
6
6
|
export { defineAction } from "./actions.js";
|
|
7
7
|
export { s } from "./action-schema.js";
|
|
8
8
|
export { limits } from "./limits.js";
|
|
9
|
+
export { formatNumber, formatVnd, formatUsd, formatDate, VIETNAM_OFFSET_MINUTES } from "./format.js";
|
|
10
|
+
export { compareVietnamese, sortVietnamese } from "./compare.js";
|
|
9
11
|
export { crypto } from "./crypto.js";
|
|
10
12
|
export { createRouter } from "./router.js";
|
|
11
13
|
export { fetch } from "./fetch.js";
|
|
@@ -391,7 +391,7 @@ codes:
|
|
|
391
391
|
| `SCRIPT_ERROR` | The handler threw an SDK error. `details.scriptErrorCode` is its code, such as `VALIDATION_ERROR` or `NOT_FOUND`, with the same safe message an HTTP route returns for that code. Any other error is reported with the message `The action handler failed`. |
|
|
392
392
|
| `TIMEOUT` | The call exceeded `timeoutMs`; `details.timeoutMs` is the limit applied. |
|
|
393
393
|
| `RATE_LIMITED` | The call went over a budget of the execution; `details.budget` describes it. |
|
|
394
|
-
| `SCRIPT_ERROR` with `details.reason` `"RESOURCE_LIMIT_EXCEEDED"` | The handler used up a sandbox resource limit:
|
|
394
|
+
| `SCRIPT_ERROR` with `details.reason` `"RESOURCE_LIMIT_EXCEEDED"` | The handler used up a sandbox resource limit: memory or stack, and on the previous runtime also statements. Runtime V2 has no statement limit: a loop that does not end runs until `TIMEOUT`, and recursion that is too deep throws a `RangeError` the handler can catch. |
|
|
395
395
|
| `PERMISSION_DENIED` | The handler let a `PermissionDeniedError` escape, for example a write in a `"read"` action. While a new version is being activated, a call may briefly fail with `details.reason` `"PROJECT_POLICY_NOT_APPROVED"` before it runs; the caller's retry runs it. |
|
|
396
396
|
| `INTERNAL_ERROR` | Another failure. |
|
|
397
397
|
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# `@cogover/sdk` API reference: Formatting and sorting
|
|
2
|
+
|
|
3
|
+
This page is part of the [`@cogover/sdk` API reference](overview.md).
|
|
4
|
+
|
|
5
|
+
## Formatting and sorting
|
|
6
|
+
|
|
7
|
+
Runtime V2 has no `Intl` object, and `toLocaleString`, `toLocaleDateString`,
|
|
8
|
+
`toLocaleTimeString`, and `localeCompare` ignore their locale and options there.
|
|
9
|
+
These functions format numbers, money, and dates and compare Vietnamese text
|
|
10
|
+
without them, and give the same text on Runtime V2, on the previous runtime,
|
|
11
|
+
and in Node.js. They are plain functions: they call no Cogover service, count
|
|
12
|
+
against no budget, and can be used anywhere, also while a module loads.
|
|
13
|
+
|
|
14
|
+
The functions were added in 0.19.0. Code that imports them can be published
|
|
15
|
+
once Cogover supports `@cogover/sdk` 0.19.0 for your Workspace; before that,
|
|
16
|
+
the publish fails with a compile error that names the function. The Runtime V2 compatibility guide shows the same functions as files
|
|
17
|
+
you can copy into a Project instead.
|
|
18
|
+
|
|
19
|
+
```typescript
|
|
20
|
+
type NumberLocale = "vi" | "en";
|
|
21
|
+
const VIETNAM_OFFSET_MINUTES: number; // 420 (GMT+7)
|
|
22
|
+
|
|
23
|
+
function formatNumber(value: number, locale?: NumberLocale, maxDecimals?: number, minDecimals?: number): string;
|
|
24
|
+
function formatVnd(value: number): string;
|
|
25
|
+
function formatUsd(value: number): string;
|
|
26
|
+
function formatDate(value: Date | number, pattern?: string, offsetMinutes?: number): string;
|
|
27
|
+
function compareVietnamese(a: string, b: string): number;
|
|
28
|
+
function sortVietnamese<T>(items: readonly T[], key?: (item: T) => string): T[];
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
### `formatNumber(value, locale?, maxDecimals?, minDecimals?)`
|
|
32
|
+
|
|
33
|
+
Formats `value` as `toLocaleString` did on the previous runtime: digits grouped
|
|
34
|
+
by three, at most `maxDecimals` decimals (default `3`), trailing zeros removed
|
|
35
|
+
down to `minDecimals` (default `0`), rounding half away from zero on the
|
|
36
|
+
shortest decimal form of the number. `locale` is `"vi"` (default: `.` groups,
|
|
37
|
+
`,` decimals) or `"en"` (`,` groups, `.` decimals). Large values are written in
|
|
38
|
+
full, never in scientific notation; `NaN`, `Infinity`, and `-Infinity` give
|
|
39
|
+
`NaN`, `∞`, and `-∞`.
|
|
40
|
+
|
|
41
|
+
Throws `TypeError` when `value` is not a number (a string, `null`, `undefined`,
|
|
42
|
+
a `bigint`), and `RangeError` for another locale, decimals that are not
|
|
43
|
+
integers from 0 to 20, or `minDecimals` greater than `maxDecimals`.
|
|
44
|
+
|
|
45
|
+
### `formatVnd(value)` and `formatUsd(value)`
|
|
46
|
+
|
|
47
|
+
`formatVnd` gives Vietnamese dong without decimals and with a no-break space
|
|
48
|
+
(`\u00a0`) before `₫`, as the previous runtime did. `formatUsd` gives US
|
|
49
|
+
dollars with two decimals and the sign before `$`. Both throw `TypeError` when
|
|
50
|
+
`value` is not a number.
|
|
51
|
+
|
|
52
|
+
### `formatDate(value, pattern?, offsetMinutes?)`
|
|
53
|
+
|
|
54
|
+
Formats a `Date` or a number of milliseconds in a fixed time zone,
|
|
55
|
+
`offsetMinutes` from UTC (default `VIETNAM_OFFSET_MINUTES`, GMT+7, no daylight
|
|
56
|
+
saving). `pattern` (default `"dd/MM/yyyy"`) accepts the tokens `yyyy`, `MM`,
|
|
57
|
+
`M`, `dd`, `d`, `HH`, `H`, `hh`, `h`, `mm`, `ss`, and `a` (`AM`/`PM`); text in
|
|
58
|
+
single quotes is copied as is. An invalid date gives `Invalid Date`. Throws
|
|
59
|
+
`TypeError` when `value` is neither a `Date` nor a number or `pattern` is not a
|
|
60
|
+
string, and `RangeError` for an offset that is not an integer from -1440 to
|
|
61
|
+
1440 or a date outside the years 1 to 9999 in that offset. The previous runtime
|
|
62
|
+
used the historical offsets of Vietnam, which differ before 1976.
|
|
63
|
+
|
|
64
|
+
### `compareVietnamese(a, b)` and `sortVietnamese(items, key?)`
|
|
65
|
+
|
|
66
|
+
`compareVietnamese` returns a negative number, zero, or a positive number in
|
|
67
|
+
the order `a.localeCompare(b, "vi")` gave on the previous runtime for
|
|
68
|
+
Vietnamese and English letters and digits: the Vietnamese alphabet
|
|
69
|
+
(`a ă â b c d đ e ê ... o ô ơ ... u ư ...`), then tone marks (none, huyền, hỏi,
|
|
70
|
+
ngã, sắc, nặng), then lower case before upper case. Text with combining marks
|
|
71
|
+
and the same text with precomposed letters compare equal. `sortVietnamese`
|
|
72
|
+
returns a sorted copy of `items`, compared by `key(item)` (default `String`).
|
|
73
|
+
|
|
74
|
+
Digits compare one by one (`"10"` before `"9"`); spaces, punctuation, and
|
|
75
|
+
symbols sort before digits and letters; other letters (`ß`, `Æ`, Greek,
|
|
76
|
+
Cyrillic...) sort after `z`, except `Ð`, `Ø`, `ı`, and `ł`, which sort as `D`,
|
|
77
|
+
`O`, `I`, and `L`. There is no numeric option.
|
|
78
|
+
|
|
79
|
+
```typescript
|
|
80
|
+
import { compareVietnamese, formatDate, formatNumber, formatVnd, sortVietnamese } from "@cogover/sdk";
|
|
81
|
+
|
|
82
|
+
formatNumber(1234567.891); // "1.234.567,891"
|
|
83
|
+
formatNumber(1234.5, "en", 2, 2); // "1,234.50"
|
|
84
|
+
formatVnd(1234567); // "1.234.567 ₫"
|
|
85
|
+
formatDate(Date.UTC(2026, 4, 29, 7, 5, 9), "dd/MM/yyyy HH:mm"); // "29/05/2026 14:05"
|
|
86
|
+
sortVietnamese(["Bình", "An", "Ân", "Đức", "Dũng"]); // ["An", "Ân", "Bình", "Dũng", "Đức"]
|
|
87
|
+
names.sort(compareVietnamese);
|
|
88
|
+
```
|
|
@@ -24,6 +24,7 @@ The reference is split into the following pages. Each page covers one area of th
|
|
|
24
24
|
| [Organization structure](organization-structure.md) | Organization structure |
|
|
25
25
|
| [Custom Module Actions](actions.md) | Custom Module Actions; Schema builder |
|
|
26
26
|
| [Processes and AI Agents](processes-and-agents.md) | Processes and AI Agents |
|
|
27
|
+
| [Formatting and sorting](formatting.md) | Numbers, money, dates, and Vietnamese sorting without `Intl` |
|
|
27
28
|
|
|
28
29
|
The sections below apply to every area: the errors every API can throw, the limits of one execution, calls that run in parallel, reading those limits in code, and the compatibility helper.
|
|
29
30
|
|
package/docs/en/usage-guide.md
CHANGED
|
@@ -405,6 +405,29 @@ With a key from a secret, these operations follow the rules of secrets and are
|
|
|
405
405
|
not available in before-change triggers. The API reference describes every option
|
|
406
406
|
and the JWT algorithm names.
|
|
407
407
|
|
|
408
|
+
## Format numbers, money, and dates
|
|
409
|
+
|
|
410
|
+
Runtime V2 has no `Intl`, and the locale methods (`toLocaleString`,
|
|
411
|
+
`toLocaleDateString`, `toLocaleTimeString`, `localeCompare`) ignore their
|
|
412
|
+
locale and options there. From 0.19.0 the SDK has functions that give the same
|
|
413
|
+
text everywhere:
|
|
414
|
+
|
|
415
|
+
```typescript
|
|
416
|
+
import { formatDate, formatNumber, formatUsd, formatVnd, sortVietnamese } from "@cogover/sdk";
|
|
417
|
+
|
|
418
|
+
formatNumber(1234567.891); // "1.234.567,891"
|
|
419
|
+
formatNumber(1234567.891, "en", 2); // "1,234,567.89"
|
|
420
|
+
formatVnd(1234567); // "1.234.567 ₫"
|
|
421
|
+
formatUsd(-1234.5); // "-$1,234.50"
|
|
422
|
+
formatDate(record.createdAt, "dd/MM/yyyy HH:mm"); // in GMT+7
|
|
423
|
+
sortVietnamese(customers, (customer) => customer.name);
|
|
424
|
+
```
|
|
425
|
+
|
|
426
|
+
They throw `TypeError` for a value that is not a number or a date, so a field
|
|
427
|
+
that is `null` is not formatted by mistake. Publishing code that imports them
|
|
428
|
+
needs a Workspace where Cogover supports SDK 0.19.0. See
|
|
429
|
+
[Formatting and sorting](api-reference/formatting.md).
|
|
430
|
+
|
|
408
431
|
## Permissions and limits
|
|
409
432
|
|
|
410
433
|
- Cogover authentication credentials are never exposed to module code. Access is
|
|
@@ -1287,11 +1310,13 @@ routes do not overlap. See [`router.route()`](api-reference/scripts-and-routes.m
|
|
|
1287
1310
|
|
|
1288
1311
|
### Keep the module fast to load
|
|
1289
1312
|
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1313
|
+
On the previous runtime every invocation loads the module code it runs; on
|
|
1314
|
+
Runtime V2 the module is loaded once when the version is prepared, and code that
|
|
1315
|
+
runs while it loads runs only once (see the Runtime V2 compatibility guide).
|
|
1316
|
+
When a module is published, Cogover can load only the code one trigger, job,
|
|
1317
|
+
action, or group of routes needs instead of the whole module, which makes the
|
|
1318
|
+
first invocation after a publish or an idle period much faster. The
|
|
1319
|
+
`cogover-dev publish` load profile shows what each entry point gets. To benefit from it:
|
|
1295
1320
|
|
|
1296
1321
|
- Define each trigger, job, or action (`defineTrigger`, `defineJob`,
|
|
1297
1322
|
`defineAction`) in a file other than `src/main.ts` and export it from there,
|
|
@@ -1305,7 +1330,7 @@ shows what each entry point gets. To benefit from it:
|
|
|
1305
1330
|
- Code that runs while a file loads may compute values and build objects of
|
|
1306
1331
|
its own: calling your own functions and static methods (also from other
|
|
1307
1332
|
files) whose code follows these rules too, `.map()`, `.filter()`, loops,
|
|
1308
|
-
`if`, `try`, `throw`, an immediately called function,
|
|
1333
|
+
`if`, `try`, `throw`, an immediately called function,
|
|
1309
1334
|
registering routes on a router the file created, filling an array, an
|
|
1310
1335
|
object, or a `Map` the same file created (also from the file's own
|
|
1311
1336
|
functions). It must not change anything outside: a variable or an object of
|
|
@@ -1313,8 +1338,8 @@ shows what each entry point gets. To benefit from it:
|
|
|
1313
1338
|
function returns), a global or a prototype, a parameter of a function, a
|
|
1314
1339
|
variable of another file from one of that file's functions.
|
|
1315
1340
|
- It must also give the same result each time it loads: no `Date.now()`,
|
|
1316
|
-
`new Date()` without arguments, `
|
|
1317
|
-
|
|
1341
|
+
`new Date()` without arguments, `Math.random()`, `Intl` (which Runtime V2
|
|
1342
|
+
does not have), `performance`, `globalThis`, globals the runtime
|
|
1318
1343
|
defines, or SDK services such as `fetch`, `crypto`, or `limits` while files
|
|
1319
1344
|
load.
|
|
1320
1345
|
- A call of a method of one of your objects or classes (`Config.select()`,
|