@boristype/ws-client 0.1.0-alpha.5 → 0.1.0-alpha.7
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 +278 -13
- package/build/client.d.ts +3 -1
- package/build/client.d.ts.map +1 -1
- package/build/client.js +3 -1
- package/build/client.js.map +1 -1
- package/build/evaluator.d.ts +8 -0
- package/build/evaluator.d.ts.map +1 -1
- package/build/evaluator.js +10 -0
- package/build/evaluator.js.map +1 -1
- package/build/hcm/api.d.ts +11 -2
- package/build/hcm/api.d.ts.map +1 -1
- package/build/hcm/api.js +14 -1
- package/build/hcm/api.js.map +1 -1
- package/build/hcm/execute.d.ts +35 -0
- package/build/hcm/execute.d.ts.map +1 -0
- package/build/hcm/execute.js +76 -0
- package/build/hcm/execute.js.map +1 -0
- package/build/hcm/packages/archive-types.d.ts +23 -0
- package/build/hcm/packages/archive-types.d.ts.map +1 -0
- package/build/hcm/packages/archive-types.js +2 -0
- package/build/hcm/packages/archive-types.js.map +1 -0
- package/build/hcm/packages/archive.d.ts +5 -0
- package/build/hcm/packages/archive.d.ts.map +1 -0
- package/build/hcm/packages/archive.js +410 -0
- package/build/hcm/packages/archive.js.map +1 -0
- package/build/hcm/packages/artifacts.d.ts +16 -0
- package/build/hcm/packages/artifacts.d.ts.map +1 -0
- package/build/hcm/packages/artifacts.js +140 -0
- package/build/hcm/packages/artifacts.js.map +1 -0
- package/build/hcm/packages/contracts.d.ts +89 -0
- package/build/hcm/packages/contracts.d.ts.map +1 -0
- package/build/hcm/packages/contracts.js +41 -0
- package/build/hcm/packages/contracts.js.map +1 -0
- package/build/hcm/packages/native.d.ts +5 -0
- package/build/hcm/packages/native.d.ts.map +1 -0
- package/build/hcm/packages/native.js +47 -0
- package/build/hcm/packages/native.js.map +1 -0
- package/build/hcm/packages/schemas.d.ts +121 -0
- package/build/hcm/packages/schemas.d.ts.map +1 -0
- package/build/hcm/packages/schemas.js +94 -0
- package/build/hcm/packages/schemas.js.map +1 -0
- package/build/hcm/packages/service.d.ts +215 -0
- package/build/hcm/packages/service.d.ts.map +1 -0
- package/build/hcm/packages/service.js +420 -0
- package/build/hcm/packages/service.js.map +1 -0
- package/build/hcm/packages/transfer.d.ts +6 -0
- package/build/hcm/packages/transfer.d.ts.map +1 -0
- package/build/hcm/packages/transfer.js +81 -0
- package/build/hcm/packages/transfer.js.map +1 -0
- package/build/hcm/schemas.d.ts +98 -0
- package/build/hcm/schemas.d.ts.map +1 -1
- package/build/hcm/schemas.js +18 -0
- package/build/hcm/schemas.js.map +1 -1
- package/build/hcm/system-info.d.ts +24 -0
- package/build/hcm/system-info.d.ts.map +1 -0
- package/build/hcm/system-info.js +57 -0
- package/build/hcm/system-info.js.map +1 -0
- package/build/hcm/xquery.d.ts +4 -3
- package/build/hcm/xquery.d.ts.map +1 -1
- package/build/hcm/xquery.js +3 -28
- package/build/hcm/xquery.js.map +1 -1
- package/build/index.d.ts +12 -1
- package/build/index.d.ts.map +1 -1
- package/build/index.js +5 -0
- package/build/index.js.map +1 -1
- package/build/soap-utils.d.ts +8 -14
- package/build/soap-utils.d.ts.map +1 -1
- package/build/soap-utils.js +205 -169
- package/build/soap-utils.js.map +1 -1
- package/build/types.d.ts +9 -0
- package/build/types.d.ts.map +1 -1
- package/build/value-projection.d.ts +8 -0
- package/build/value-projection.d.ts.map +1 -0
- package/build/value-projection.js +101 -0
- package/build/value-projection.js.map +1 -0
- package/build/xquery.d.ts +28 -0
- package/build/xquery.d.ts.map +1 -0
- package/build/xquery.js +63 -0
- package/build/xquery.js.map +1 -0
- package/package.json +7 -2
- package/resources/execute.bs +40 -0
- package/resources/package-operation.bs +318 -0
- package/resources/value-projection.bs +79 -0
- package/resources/xquery.bs +16 -24
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { WshcmValue } from "./types.js";
|
|
2
|
+
/** Options for bounded XQuery results; row limits do not bound database work. */
|
|
3
|
+
export interface XQueryOptions {
|
|
4
|
+
/** Maximum returned rows (1–1000, default 100); materializes one extra row. */
|
|
5
|
+
maxRows?: number;
|
|
6
|
+
}
|
|
7
|
+
/** Plain typed data projected from server-side XQuery results. */
|
|
8
|
+
export interface XQueryResult {
|
|
9
|
+
/** Recursive ordinary records/arrays; integers are bigint and dates ISO strings. */
|
|
10
|
+
rows: WshcmValue[];
|
|
11
|
+
/** Number of complete returned rows. */
|
|
12
|
+
returnedRows: number;
|
|
13
|
+
/** Whether another row was excluded by a row or output limit. */
|
|
14
|
+
truncated: boolean;
|
|
15
|
+
/** The first result limit reached, or null for complete results. */
|
|
16
|
+
limitReason: "rows" | "output" | null;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Execute XQuery once through an evaluator and decode the private typed carrier.
|
|
20
|
+
* Query text is passed unchanged as data. No retries, read-only validation,
|
|
21
|
+
* database work bound or transport cancellation guarantee are provided.
|
|
22
|
+
* Results are limited to whole rows, depth 32, 10,000 values and 256 KiB of
|
|
23
|
+
* JSON-compatible data. Strings preserve CR/LF; native dates become ISO strings.
|
|
24
|
+
*/
|
|
25
|
+
export declare function executeXQuery(evaluator: {
|
|
26
|
+
eval(code: string): Promise<unknown>;
|
|
27
|
+
}, query: string, options?: XQueryOptions): Promise<XQueryResult>;
|
|
28
|
+
//# sourceMappingURL=xquery.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"xquery.d.ts","sourceRoot":"","sources":["../src/xquery.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAG7C,iFAAiF;AACjF,MAAM,WAAW,aAAa;IAC5B,+EAA+E;IAC/E,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,kEAAkE;AAClE,MAAM,WAAW,YAAY;IAC3B,oFAAoF;IACpF,IAAI,EAAE,UAAU,EAAE,CAAC;IACnB,wCAAwC;IACxC,YAAY,EAAE,MAAM,CAAC;IACrB,iEAAiE;IACjE,SAAS,EAAE,OAAO,CAAC;IACnB,oEAAoE;IACpE,WAAW,EAAE,MAAM,GAAG,QAAQ,GAAG,IAAI,CAAC;CACvC;AASD;;;;;;GAMG;AACH,wBAAsB,aAAa,CACjC,SAAS,EAAE;IAAE,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;CAAE,EACnD,KAAK,EAAE,MAAM,EACb,OAAO,GAAE,aAAkB,GAC1B,OAAO,CAAC,YAAY,CAAC,CAiDvB"}
|
package/build/xquery.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { projectionSource, projectionDecoder, carrierRecord as record, carrierArray as array } from "./value-projection.js";
|
|
3
|
+
const template = readFileSync(new URL("../resources/xquery.bs", import.meta.url), "utf8");
|
|
4
|
+
const maxBytes = 262144;
|
|
5
|
+
function invalid(message) {
|
|
6
|
+
throw new Error(`Invalid XQuery response: ${message}`);
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Execute XQuery once through an evaluator and decode the private typed carrier.
|
|
10
|
+
* Query text is passed unchanged as data. No retries, read-only validation,
|
|
11
|
+
* database work bound or transport cancellation guarantee are provided.
|
|
12
|
+
* Results are limited to whole rows, depth 32, 10,000 values and 256 KiB of
|
|
13
|
+
* JSON-compatible data. Strings preserve CR/LF; native dates become ISO strings.
|
|
14
|
+
*/
|
|
15
|
+
export async function executeXQuery(evaluator, query, options = {}) {
|
|
16
|
+
if (typeof query !== "string" ||
|
|
17
|
+
!query.trim() ||
|
|
18
|
+
!query.isWellFormed() ||
|
|
19
|
+
query.includes("\0") ||
|
|
20
|
+
Buffer.byteLength(query, "utf8") > 65536) {
|
|
21
|
+
throw new TypeError("XQuery query must be nonblank, well-formed text without NUL, within 65536 UTF-8 bytes");
|
|
22
|
+
}
|
|
23
|
+
const maxRows = options.maxRows === undefined ? 100 : options.maxRows;
|
|
24
|
+
if (!Number.isInteger(maxRows) || maxRows < 1 || maxRows > 1000)
|
|
25
|
+
throw new TypeError("XQuery maxRows must be an integer from 1 to 1000");
|
|
26
|
+
// JSON string syntax is valid BS string syntax; escape line separator literals.
|
|
27
|
+
const literal = JSON.stringify(query)
|
|
28
|
+
.replace(/\u2028/g, "\\u2028")
|
|
29
|
+
.replace(/\u2029/g, "\\u2029");
|
|
30
|
+
const script = template.replace(/\$\{(queryLiteral|maxRows|projectionSource)\}/g, (_, name) => name === "projectionSource" ? projectionSource : name === "queryLiteral" ? literal : String(maxRows));
|
|
31
|
+
const response = await evaluator.eval(script);
|
|
32
|
+
if (!record(response, ["rows", "returnedRows", "truncated", "limitReason"]))
|
|
33
|
+
invalid("expected the result envelope");
|
|
34
|
+
const { rows: carrier, returnedRows, truncated, limitReason } = response;
|
|
35
|
+
if (!array(carrier) ||
|
|
36
|
+
typeof returnedRows !== "bigint" ||
|
|
37
|
+
returnedRows < 0n ||
|
|
38
|
+
returnedRows > BigInt(maxRows) ||
|
|
39
|
+
returnedRows !== BigInt(carrier.length))
|
|
40
|
+
invalid("inconsistent row count");
|
|
41
|
+
if (typeof truncated !== "boolean" ||
|
|
42
|
+
(limitReason !== null && limitReason !== "rows" && limitReason !== "output") ||
|
|
43
|
+
truncated !== (limitReason !== null))
|
|
44
|
+
invalid("inconsistent truncation metadata");
|
|
45
|
+
if (limitReason === "rows" && returnedRows !== BigInt(maxRows))
|
|
46
|
+
invalid("row limit contradicts maxRows");
|
|
47
|
+
const decode = projectionDecoder();
|
|
48
|
+
const rows = carrier.map((row) => decode(row, 0));
|
|
49
|
+
const result = { rows, returnedRows: Number(returnedRows), truncated, limitReason };
|
|
50
|
+
// Conservative size accounting only: presentation policy remains the caller's.
|
|
51
|
+
// Decimal strings bound both safe-number and large-decimal-string bigint JSON.
|
|
52
|
+
const bounded = JSON.stringify(result, (_, value) => {
|
|
53
|
+
if (typeof value === "bigint")
|
|
54
|
+
return value.toString();
|
|
55
|
+
if (typeof value === "number" && !Number.isFinite(value))
|
|
56
|
+
return String(value);
|
|
57
|
+
return value === undefined ? null : value;
|
|
58
|
+
});
|
|
59
|
+
if (Buffer.byteLength(bounded, "utf8") > maxBytes)
|
|
60
|
+
invalid("JSON-compatible output exceeds 256 KiB limit");
|
|
61
|
+
return result;
|
|
62
|
+
}
|
|
63
|
+
//# sourceMappingURL=xquery.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"xquery.js","sourceRoot":"","sources":["../src/xquery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAEvC,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,aAAa,IAAI,MAAM,EAAE,YAAY,IAAI,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAoB5H,MAAM,QAAQ,GAAG,YAAY,CAAC,IAAI,GAAG,CAAC,wBAAwB,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,CAAC;AAC1F,MAAM,QAAQ,GAAG,MAAM,CAAC;AAExB,SAAS,OAAO,CAAC,OAAe;IAC9B,MAAM,IAAI,KAAK,CAAC,4BAA4B,OAAO,EAAE,CAAC,CAAC;AACzD,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,aAAa,CACjC,SAAmD,EACnD,KAAa,EACb,UAAyB,EAAE;IAE3B,IACE,OAAO,KAAK,KAAK,QAAQ;QACzB,CAAC,KAAK,CAAC,IAAI,EAAE;QACb,CAAC,KAAK,CAAC,YAAY,EAAE;QACrB,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC;QACpB,MAAM,CAAC,UAAU,CAAC,KAAK,EAAE,MAAM,CAAC,GAAG,KAAK,EACxC,CAAC;QACD,MAAM,IAAI,SAAS,CAAC,uFAAuF,CAAC,CAAC;IAC/G,CAAC;IACD,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC;IACtE,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,OAAO,CAAC,IAAI,OAAO,GAAG,CAAC,IAAI,OAAO,GAAG,IAAI;QAAE,MAAM,IAAI,SAAS,CAAC,kDAAkD,CAAC,CAAC;IACzI,gFAAgF;IAChF,MAAM,OAAO,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC;SAClC,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC;SAC7B,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;IACjC,MAAM,MAAM,GAAG,QAAQ,CAAC,OAAO,CAAC,gDAAgD,EAAE,CAAC,CAAC,EAAE,IAAY,EAAE,EAAE,CACpG,IAAI,KAAK,kBAAkB,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC,IAAI,KAAK,cAAc,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CACrG,CAAC;IACF,MAAM,QAAQ,GAAG,MAAM,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC9C,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC,MAAM,EAAE,cAAc,EAAE,WAAW,EAAE,aAAa,CAAC,CAAC;QAAE,OAAO,CAAC,8BAA8B,CAAC,CAAC;IACrH,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,WAAW,EAAE,GAAG,QAAQ,CAAC;IACzE,IACE,CAAC,KAAK,CAAC,OAAO,CAAC;QACf,OAAO,YAAY,KAAK,QAAQ;QAChC,YAAY,GAAG,EAAE;QACjB,YAAY,GAAG,MAAM,CAAC,OAAO,CAAC;QAC9B,YAAY,KAAK,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC;QAEvC,OAAO,CAAC,wBAAwB,CAAC,CAAC;IACpC,IACE,OAAO,SAAS,KAAK,SAAS;QAC9B,CAAC,WAAW,KAAK,IAAI,IAAI,WAAW,KAAK,MAAM,IAAI,WAAW,KAAK,QAAQ,CAAC;QAC5E,SAAS,KAAK,CAAC,WAAW,KAAK,IAAI,CAAC;QAEpC,OAAO,CAAC,kCAAkC,CAAC,CAAC;IAC9C,IAAI,WAAW,KAAK,MAAM,IAAI,YAAY,KAAK,MAAM,CAAC,OAAO,CAAC;QAAE,OAAO,CAAC,+BAA+B,CAAC,CAAC;IACzG,MAAM,MAAM,GAAG,iBAAiB,EAAE,CAAC;IACnC,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC;IAClD,MAAM,MAAM,GAAiB,EAAE,IAAI,EAAE,YAAY,EAAE,MAAM,CAAC,YAAY,CAAC,EAAE,SAAS,EAAE,WAAW,EAAE,CAAC;IAClG,+EAA+E;IAC/E,+EAA+E;IAC/E,MAAM,OAAO,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,KAAc,EAAE,EAAE;QAC3D,IAAI,OAAO,KAAK,KAAK,QAAQ;YAAE,OAAO,KAAK,CAAC,QAAQ,EAAE,CAAC;QACvD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC;YAAE,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;QAC/E,OAAO,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC;IAC5C,CAAC,CAAC,CAAC;IACH,IAAI,MAAM,CAAC,UAAU,CAAC,OAAO,EAAE,MAAM,CAAC,GAAG,QAAQ;QAAE,OAAO,CAAC,8CAA8C,CAAC,CAAC;IAC3G,OAAO,MAAM,CAAC;AAChB,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@boristype/ws-client",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.7",
|
|
4
4
|
"description": "WSHCM SOAP client — клиент для работы с WebSoft HCM через SP-XML API",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "build/index.js",
|
|
@@ -13,10 +13,12 @@
|
|
|
13
13
|
"dependencies": {
|
|
14
14
|
"fast-xml-parser": "^5.11.2",
|
|
15
15
|
"saxes": "^6.0.0",
|
|
16
|
+
"yauzl": "3.4.0",
|
|
16
17
|
"zod": "^4.6.7"
|
|
17
18
|
},
|
|
18
19
|
"devDependencies": {
|
|
19
20
|
"@types/node": "^24.19.2",
|
|
21
|
+
"@types/yauzl": "3.4.0",
|
|
20
22
|
"typescript": "^6.0.3"
|
|
21
23
|
},
|
|
22
24
|
"keywords": [
|
|
@@ -44,6 +46,9 @@
|
|
|
44
46
|
"scripts": {
|
|
45
47
|
"build": "node tools/prepare-runtime.mjs && tsc",
|
|
46
48
|
"build:runtime": "node tools/prepare-runtime.mjs",
|
|
47
|
-
"test": "node --test test/*.test.mjs"
|
|
49
|
+
"test": "node --test test/*.test.mjs",
|
|
50
|
+
"test:e2e:values": "node --test --test-concurrency=1 test/e2e/values.mjs",
|
|
51
|
+
"test:e2e:xquery": "node --test --test-concurrency=1 test/e2e/xquery.mjs",
|
|
52
|
+
"test:e2e:packages": "node test/e2e/packages.mjs"
|
|
48
53
|
}
|
|
49
54
|
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
${projectionSource}
|
|
2
|
+
var _execSource = ${codeLiteral};
|
|
3
|
+
var _execOutput = [];
|
|
4
|
+
var _execChars = 0;
|
|
5
|
+
var _execTruncated = false;
|
|
6
|
+
// Experimental call-local diagnostics; practical usefulness remains to be evaluated.
|
|
7
|
+
function print(value) {
|
|
8
|
+
if (_execTruncated) return value;
|
|
9
|
+
var text;
|
|
10
|
+
if (DataType(value) == 'string') text = value;
|
|
11
|
+
else if (DataType(value) == 'undefined') text = 'undefined';
|
|
12
|
+
else text = EncodeJson(value);
|
|
13
|
+
var encoded = EncodeJson(text);
|
|
14
|
+
var size = StrCharCount(encoded);
|
|
15
|
+
if ((ArrayCount(_execOutput) >= 256) || ((_execChars + size) > 16000)) {
|
|
16
|
+
_execTruncated = true;
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
_execOutput.push(encoded);
|
|
20
|
+
_execChars = _execChars + size;
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
function _execRun() {
|
|
24
|
+
return eval(_execSource);
|
|
25
|
+
}
|
|
26
|
+
var _execPhase = 'execution';
|
|
27
|
+
try {
|
|
28
|
+
var _execValue = _execRun();
|
|
29
|
+
_execPhase = 'result';
|
|
30
|
+
var _execProjected = _btValueProject(_execValue, 0);
|
|
31
|
+
// Bounds the response after execution; it never stops or rolls back the script.
|
|
32
|
+
if (StrCharCount(EncodeJson(_execProjected)) > 48000) throw 'Execution result exceeds output limit (48000 carrier characters)';
|
|
33
|
+
return {ok:true,value:_execProjected,output:_execOutput,outputTruncated:_execTruncated,error:null};
|
|
34
|
+
} catch (_execError) {
|
|
35
|
+
var _execMessage;
|
|
36
|
+
try { _execMessage = String(_execError); }
|
|
37
|
+
catch (_execFormatError) { _execMessage = 'Unable to format native exception'; }
|
|
38
|
+
if (StrCharCount(_execMessage) > 2000) _execMessage = StrLeftCharRange(_execMessage, 2000);
|
|
39
|
+
return {ok:false,value:null,output:_execOutput,outputTruncated:_execTruncated,error:{phase:_execPhase,message:EncodeJson(_execMessage)}};
|
|
40
|
+
}
|
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
function BtPackageUuid(v) {
|
|
2
|
+
if (StrCharCount(v) != 36) return false;
|
|
3
|
+
var k;
|
|
4
|
+
for (k = 0; k < 36; k++) {
|
|
5
|
+
if (k == 8 || k == 13 || k == 18 || k == 23) { if (String(v).charAt(k) != '-') return false; }
|
|
6
|
+
else if (!StrContains('0123456789abcdef', String(v).charAt(k))) return false;
|
|
7
|
+
}
|
|
8
|
+
return true;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// Native package operations: physical owned transfer/receipt files, logical schema document.
|
|
12
|
+
function BtPackageOperation(r) {
|
|
13
|
+
var phase = 'validate';
|
|
14
|
+
var status = 'not_attempted';
|
|
15
|
+
var code = 'InvalidInput';
|
|
16
|
+
var receipt = null;
|
|
17
|
+
var root = '';
|
|
18
|
+
var accountId = ''; var targetId = '';
|
|
19
|
+
function owned(value) { if (value.accountId != accountId || value.targetId != targetId) fail('ContextMismatch','Receipt belongs to another target/account'); return value; }
|
|
20
|
+
var receiptPath = '';
|
|
21
|
+
var i; var j; var p; var o; var d; var result; var snapshot; var items; var settings;
|
|
22
|
+
function opt(obj, key) { try { return obj[key]; } catch(missing) { return undefined; } }
|
|
23
|
+
function fail(c, m) { code = c; throw m; }
|
|
24
|
+
function persist() { PutFileData(receiptPath, EncodeJson(receipt)); }
|
|
25
|
+
function advance(v) { phase = v; receipt.phase = v; persist(); }
|
|
26
|
+
function xml(doc) {
|
|
27
|
+
var s = doc.TopElem.GetXml();
|
|
28
|
+
if (StrCharCount(s) > 33554432) fail('OutputLimit', 'Schema XML exceeds 32 MiB');
|
|
29
|
+
return s;
|
|
30
|
+
}
|
|
31
|
+
function summary(v) { return {schemaId:String(v.id), name:String(v.name), objectCount:ArrayCount(v.objects)}; }
|
|
32
|
+
function details(v, offset, limit) {
|
|
33
|
+
var x = summary(v); var k; var f; var entry;
|
|
34
|
+
x.objects = []; x.offset = offset; x.limit = limit;
|
|
35
|
+
for (k = offset; k < ArrayCount(v.objects) && k < offset + limit; k++) {
|
|
36
|
+
f = v.objects[k]; x.objects.push({id:StrInt(f.id),type:String(f.type),name:String(f.name),editable:f.modify == true});
|
|
37
|
+
}
|
|
38
|
+
x.settings = {processCustomTemplates:v.process_custom_templates == true,processAccessRoles:v.process_access_roles == true,customTemplates:[],files:[]};
|
|
39
|
+
if (ArrayCount(v.custom_templates) > 1000 || ArrayCount(v.files) > 1000) fail('OutputLimit','Schema settings exceed limit');
|
|
40
|
+
for(k = 0; k < ArrayCount(v.custom_templates); k++) x.settings.customTemplates.push(String(v.custom_templates[k].catalog_name));
|
|
41
|
+
for(k = 0; k < ArrayCount(v.files); k++) {
|
|
42
|
+
f = v.files[k];
|
|
43
|
+
entry = {code:String(f.code),type:String(f.type),url:String(f.url)};
|
|
44
|
+
if(String(f.base_url) != '') entry.baseUrl = String(f.base_url);
|
|
45
|
+
x.settings.files.push(entry);
|
|
46
|
+
}
|
|
47
|
+
return x;
|
|
48
|
+
}
|
|
49
|
+
function add(v) {
|
|
50
|
+
var k; var res;
|
|
51
|
+
for(k = 0; k < ArrayCount(r.objectIds); k++) {
|
|
52
|
+
try {
|
|
53
|
+
res = tools.add_object_to_package(null,Int(r.objectIds[k]),null,v,{apply_to_all:true,add_files:r.includeFiles,add_roles:r.includeCategories,add_sections:r.includeAssessmentItems,add_foreign_elem_objects:r.includeRelatedObjects});
|
|
54
|
+
if(res.error != 0) errors.push(String(r.objectIds[k]) + ': ' + String(res.message));
|
|
55
|
+
} catch(e) { errors.push(String(r.objectIds[k]) + ': ' + StrLeftRange(String(e),500)); }
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
var errors = [];
|
|
59
|
+
try {
|
|
60
|
+
if (!BtPackageUuid(r.operationId)) fail('InvalidInput','Invalid operation UUID');
|
|
61
|
+
// Missing evidence cannot establish that a historical mutation was never attempted.
|
|
62
|
+
if (r.operation == 'status') {phase = 'receipt';status = 'unknown';code = 'ReceiptUnavailable';}
|
|
63
|
+
accountId = StrInt(tools.get_cur_user_id());
|
|
64
|
+
if(accountId == '' || accountId == '0') fail('ContextUnavailable','Authenticated account identity required');
|
|
65
|
+
if (!IsDirectory('x-local://trash/boristype_packages')) CreateDirectory('x-local://trash/boristype_packages');
|
|
66
|
+
var identityPath = UrlToFilePath('x-local://trash/boristype_packages/identity.txt');
|
|
67
|
+
if (!FilePathExists(identityPath)) PutFileData(identityPath,tools.random_string(32));
|
|
68
|
+
targetId = String(LoadFileData(identityPath));
|
|
69
|
+
root = 'x-local://trash/boristype_packages/' + r.operationId;
|
|
70
|
+
receiptPath = UrlToFilePath(root + '/receipt.json');
|
|
71
|
+
if (r.operation == 'status') {
|
|
72
|
+
result = owned(ParseJson(LoadFileData(receiptPath)));
|
|
73
|
+
return {ok:true,body:result};
|
|
74
|
+
}
|
|
75
|
+
if (r.operation == 'read_chunk') {
|
|
76
|
+
owned(ParseJson(LoadFileData(receiptPath)));
|
|
77
|
+
if (r.start < 0 || r.end < r.start || r.end - r.start > 262144 || r.end > 134217728) fail('InvalidInput','Invalid chunk range');
|
|
78
|
+
return {ok:true,body:{data:Base64Encode(LoadFileDataRange(UrlToFilePath(root + '/archive.zip'),r.start,r.end))}};
|
|
79
|
+
}
|
|
80
|
+
if (r.operation == 'finish_export') {
|
|
81
|
+
receipt = owned(ParseJson(LoadFileData(receiptPath)));
|
|
82
|
+
if(receipt.operation != 'export' || receipt.phase != 'exported') fail('Conflict','Export already finalized');
|
|
83
|
+
receipt.status = r.partial ? 'partial' : receipt.status;
|
|
84
|
+
receipt.verification = 'archive_membership';receipt.phase = 'downloaded';persist();
|
|
85
|
+
return {ok:true,body:receipt};
|
|
86
|
+
}
|
|
87
|
+
if (r.operation == 'seal_upload') {
|
|
88
|
+
receipt = owned(ParseJson(LoadFileData(receiptPath)));
|
|
89
|
+
if (receipt.operation != 'upload' || receipt.status != 'running') fail('Conflict','Upload is not writable');
|
|
90
|
+
if (FileSize(UrlToFilePath(root + '/archive.zip')) != r.sizeBytes) fail('Conflict','Upload size changed');
|
|
91
|
+
PutFileData(UrlToFilePath(root + '/binding.json'),EncodeJson({sha256:r.sha256,sizeBytes:r.sizeBytes}));
|
|
92
|
+
receipt.phase = 'uploaded';receipt.status = 'completed';persist();
|
|
93
|
+
return {ok:true,body:receipt};
|
|
94
|
+
}
|
|
95
|
+
if (r.operation == 'write_chunk') {
|
|
96
|
+
receipt = owned(ParseJson(LoadFileData(receiptPath)));
|
|
97
|
+
if (receipt.operation != 'upload' || receipt.status != 'running') fail('Conflict','Upload is not writable');
|
|
98
|
+
if (r.start < 0 || r.end <= r.start || r.end - r.start > 262144 || r.end > 134217728 || StrCharCount(r.data) > 349528) fail('InvalidInput','Invalid chunk range');
|
|
99
|
+
if (FileSize(UrlToFilePath(root + '/archive.zip')) != r.start) fail('Conflict','Nonsequential upload');
|
|
100
|
+
PutFileDataRange(UrlToFilePath(root + '/archive.zip'),r.start,r.end,Base64Decode(r.data));
|
|
101
|
+
return {ok:true,body:{sizeBytes:FileSize(UrlToFilePath(root + '/archive.zip'))}};
|
|
102
|
+
}
|
|
103
|
+
if (r.operation == 'list' || r.operation == 'get') {
|
|
104
|
+
d = OpenDoc('x-local://' + DefaultDb + '/lists/wtv_package_objects.xml');
|
|
105
|
+
snapshot = xml(d);
|
|
106
|
+
if (r.operation == 'get') result = details(d.TopElem.GetChildByKey(r.schemaId),r.offset,r.limit);
|
|
107
|
+
else {
|
|
108
|
+
items = [];
|
|
109
|
+
for (i = r.offset; i < ArrayCount(d.TopElem) && i < r.offset + r.limit; i++) items.push(summary(d.TopElem[i]));
|
|
110
|
+
result = {items:items,total:ArrayCount(d.TopElem),offset:r.offset,limit:r.limit};
|
|
111
|
+
}
|
|
112
|
+
return {ok:true,body:{snapshot:snapshot,result:result}};
|
|
113
|
+
}
|
|
114
|
+
if (r.operation != 'save' && r.operation != 'delete' && r.operation != 'add' && r.operation != 'remove' && r.operation != 'export' && r.operation != 'upload' && r.operation != 'preview' && r.operation != 'import') fail('InvalidInput','Unknown operation');
|
|
115
|
+
var continuingUpload = false;
|
|
116
|
+
if (FilePathExists(receiptPath)) {
|
|
117
|
+
var previous = owned(ParseJson(LoadFileData(receiptPath)));
|
|
118
|
+
continuingUpload = r.operation == 'preview' && opt(r,'sourceId') == r.operationId && previous.operation == 'upload' && previous.phase == 'uploaded';
|
|
119
|
+
if(!continuingUpload) fail('Conflict','Operation already dispatched; query its receipt');
|
|
120
|
+
}
|
|
121
|
+
if (!IsDirectory('x-local://trash/boristype_packages')) CreateDirectory('x-local://trash/boristype_packages');
|
|
122
|
+
if(!continuingUpload) CreateDirectory(root);
|
|
123
|
+
receipt = {accountId:accountId,targetId:targetId,operationId:r.operationId,operation:r.operation,phase:'prepared',status:'running',verification:'platform_report_only',error:'',reportIds:[],downloadIds:[]};
|
|
124
|
+
persist();
|
|
125
|
+
if (r.operation == 'upload') {
|
|
126
|
+
PutFileData(UrlToFilePath(root + '/archive.zip'),'');
|
|
127
|
+
return {ok:true,body:receipt};
|
|
128
|
+
}
|
|
129
|
+
if (r.operation == 'preview' || r.operation == 'import') {
|
|
130
|
+
result = BtPackagePreview(r,root,receipt,receiptPath);
|
|
131
|
+
if(opt(result,'nativeFailure') == true) return {ok:false,code:result.code,message:result.message,phase:result.phase,status:result.status};
|
|
132
|
+
return {ok:true,body:result};
|
|
133
|
+
}
|
|
134
|
+
phase = 'read';
|
|
135
|
+
if (opt(r,'schemaId') != undefined || r.operation != 'export') {
|
|
136
|
+
d = OpenDoc('x-local://' + DefaultDb + '/lists/wtv_package_objects.xml');
|
|
137
|
+
snapshot = xml(d);
|
|
138
|
+
if (opt(r,'schemaId') != undefined && snapshot != r.expected) fail('Conflict','Common schema document changed; read again');
|
|
139
|
+
if (opt(r,'schemaId') != undefined) p = d.TopElem.GetChildByKey(r.schemaId);
|
|
140
|
+
else {p = d.TopElem.AddChild();p.id = r.operationId;}
|
|
141
|
+
} else p = OpenNewDoc('x-local://wtv/wtv_package_objects.xmd').TopElem.AddChild();
|
|
142
|
+
if (r.operation == 'save') {
|
|
143
|
+
if(opt(r,'name') != undefined) p.name = r.name;
|
|
144
|
+
if(opt(r,'settings') != undefined) {
|
|
145
|
+
settings = r.settings;
|
|
146
|
+
if(opt(settings,'processCustomTemplates') != undefined) p.process_custom_templates = settings.processCustomTemplates;
|
|
147
|
+
if(opt(settings,'processAccessRoles') != undefined) p.process_access_roles = settings.processAccessRoles;
|
|
148
|
+
if(opt(settings,'customTemplates') != undefined) {p.custom_templates.Clear();for(i = 0; i < ArrayCount(settings.customTemplates); i++) p.custom_templates.AddChild().catalog_name = settings.customTemplates[i];}
|
|
149
|
+
if(opt(settings,'files') != undefined) {
|
|
150
|
+
p.files.Clear();for(i = 0; i < ArrayCount(settings.files); i++) {
|
|
151
|
+
o = p.files.AddChild();o.code = settings.files[i].code;o.type = settings.files[i].type;o.url = settings.files[i].url;
|
|
152
|
+
if(opt(settings.files[i],'baseUrl') != undefined) o.base_url = settings.files[i].baseUrl;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
if(opt(r,'editable') != undefined) for(i = 0; i < ArrayCount(r.editable); i++) p.objects.GetChildByKey(Int(r.editable[i].id)).modify = r.editable[i].editable;
|
|
157
|
+
}
|
|
158
|
+
if(r.operation == 'add' || (r.operation == 'export' && opt(r,'objectIds') != undefined)) add(p);
|
|
159
|
+
if(r.operation == 'remove') for(i = 0; i < ArrayCount(r.objectIds); i++) p.objects.DeleteChildByKey(Int(r.objectIds[i]));
|
|
160
|
+
if(r.operation == 'delete') d.TopElem.DeleteChildByKey(r.schemaId);
|
|
161
|
+
if(r.operation == 'export') {
|
|
162
|
+
advance('export'); status = 'unknown';
|
|
163
|
+
var wanted = [];
|
|
164
|
+
if(ArrayCount(p.objects) > 10000) fail('OutputLimit','Export exceeds 10000 objects');
|
|
165
|
+
for(i = 0; i < ArrayCount(p.objects); i++) wanted.push(StrInt(p.objects[i].id));
|
|
166
|
+
result = tools.create_list_package(root + '/archive.zip',p);
|
|
167
|
+
var size = FileSize(UrlToFilePath(root + '/archive.zip'));
|
|
168
|
+
if(size > 134217728) fail('OutputLimit','Archive exceeds 128 MiB');
|
|
169
|
+
receipt.status = result.error == 0 && ArrayCount(errors) == 0 ? 'completed' : 'partial';
|
|
170
|
+
receipt.error = StrLeftRange(String(result.error_text),2000);
|
|
171
|
+
var exportReports = ArraySelectAll(XQuery('for $r in action_reports where $r/type = "create_package" and $r/data_file_url = ' + CodeLiteral(root + '/archive.zip') + ' return $r'));
|
|
172
|
+
for(i = 0; i < ArrayCount(exportReports) && i < 1000; i++) receipt.reportIds.push(StrInt(exportReports[i].id));
|
|
173
|
+
receipt.phase = 'exported';persist();
|
|
174
|
+
return {ok:true,body:{sizeBytes:size,requestedIds:wanted,errors:errors,operation:receipt}};
|
|
175
|
+
}
|
|
176
|
+
advance('recheck');
|
|
177
|
+
if(xml(OpenDoc('x-local://' + DefaultDb + '/lists/wtv_package_objects.xml')) != snapshot) fail('Conflict','Common schema document changed before Save');
|
|
178
|
+
advance('save');status = 'unknown';d.Save();
|
|
179
|
+
receipt.phase = 'saved';receipt.status = ArrayCount(errors) == 0 ? 'completed' : 'partial';persist();
|
|
180
|
+
return {ok:true,body:{schemaId:(r.operation == 'delete' ? r.schemaId : String(p.id)),operation:receipt,errors:errors}};
|
|
181
|
+
} catch(e) {
|
|
182
|
+
var message = StrLeftRange(String(e),2000);
|
|
183
|
+
if(receipt != null && receipt.operation == r.operation) {
|
|
184
|
+
receipt.phase = phase;receipt.status = status == 'unknown' ? 'unknown' : 'failed';receipt.error = message;
|
|
185
|
+
try { persist(); } catch(ignore) {}
|
|
186
|
+
}
|
|
187
|
+
return {ok:false,code:(code == 'InvalidInput' && phase != 'validate' ? 'PlatformError' : code),message:message,phase:phase,status:(status == 'unknown' ? 'unknown' : 'not_attempted')};
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
// Rebuild the native preview immediately before apply. The saved form is evidence,
|
|
193
|
+
// never permission to skip fresh conflict/version/reimport checks.
|
|
194
|
+
function BtPackagePreview(r,root,receipt,receiptPath) {
|
|
195
|
+
var form = null; var paths = []; var i; var j; var k; var p; var o; var known; var current;
|
|
196
|
+
var code = 'PlatformError'; var phase = 'preview'; var applied = false;
|
|
197
|
+
var parts = []; var before = []; var selectedCount = 0; var reportUrls = [];
|
|
198
|
+
function persist() { PutFileData(receiptPath,EncodeJson(receipt)); }
|
|
199
|
+
function fail(c,m) { code = c; throw m; }
|
|
200
|
+
function has(values,key) { try { return values[key] == true; } catch(missing) {return false;} }
|
|
201
|
+
function cleanup() {
|
|
202
|
+
var n;
|
|
203
|
+
PutFileData(UrlToFilePath(root + '/owned-paths.json'),EncodeJson(paths));
|
|
204
|
+
for(n = ArrayCount(paths) - 1; n >= 0; n--) { if(paths[n] != '') {try {DeleteDirectory(paths[n]);} catch(ignore) {}} }
|
|
205
|
+
}
|
|
206
|
+
try {
|
|
207
|
+
if(!BtPackageUuid(r.sourceId)) fail('InvalidInput','Invalid source UUID');
|
|
208
|
+
var source = 'x-local://trash/boristype_packages/' + r.sourceId;
|
|
209
|
+
var owner = ParseJson(LoadFileData(UrlToFilePath(source + '/receipt.json')));
|
|
210
|
+
if(owner.targetId != receipt.targetId || owner.accountId != receipt.accountId) fail('ContextMismatch','Archive belongs to another target/account');
|
|
211
|
+
var binding = ParseJson(LoadFileData(UrlToFilePath(source + '/binding.json')));
|
|
212
|
+
if(binding.sha256 != r.sha256 || (owner.phase != 'inspected' && !(r.operation == 'preview' && r.sourceId == r.operationId && owner.phase == 'prepared')) || FileSize(UrlToFilePath(source + '/archive.zip')) != binding.sizeBytes) fail('Conflict','Uploaded archive binding changed');
|
|
213
|
+
var url = source + '/archive.zip';
|
|
214
|
+
form = tools.get_package_log(url,{bDeleteTempDir:false,bCheckVersion:false});
|
|
215
|
+
paths.push(String(form.temp_package_url));
|
|
216
|
+
for(i = 0; i < ArrayCount(form.download_packages); i++) paths.push(String(form.download_packages[i].temp_package_url));
|
|
217
|
+
PutFileData(UrlToFilePath(root + '/owned-paths.json'),EncodeJson(paths));
|
|
218
|
+
if(form.error != 0) fail('PreviewError',StrLeftRange(String(form.error_text),1800));
|
|
219
|
+
if(ArrayCount(form.download_packages) != ArrayCount(r.manifest)) fail('ManifestMismatch','Native package count differs from inspected archive');
|
|
220
|
+
// get_package_log assigns a random ID for a standalone update.xml ZIP.
|
|
221
|
+
// Build a descriptor only in its owned extraction directory; archive bytes stay unchanged.
|
|
222
|
+
if(ArrayCount(r.manifest) == 1 && r.manifest[0].url == 'update.xml' && String(form.download_packages[0].url) == '') {
|
|
223
|
+
p = form.download_packages[0];
|
|
224
|
+
if(String(p.type) != 'objects') fail('ManifestMismatch','Standalone package is not objects');
|
|
225
|
+
p.id = r.manifest[0].id;p.url = 'update.xml';
|
|
226
|
+
var descriptor = OpenNewDoc('x-local://wtv/wtv_form_download_packages.xmd');
|
|
227
|
+
var descriptorPart = descriptor.TopElem.AddChild();
|
|
228
|
+
descriptorPart.id = p.id;descriptorPart.type = 'objects';descriptorPart.url = 'update.xml';
|
|
229
|
+
descriptor.Save(String(form.temp_package_url) + '/desc.xml');
|
|
230
|
+
}
|
|
231
|
+
var serverVersion = String(tools.get_version('wtv'));
|
|
232
|
+
var info; var found; var manifest; var version; var type; var row; var rows; var downloads; var existing;
|
|
233
|
+
for(i = 0; i < ArrayCount(form.download_packages); i++) {
|
|
234
|
+
p = form.download_packages[i]; manifest = null;
|
|
235
|
+
for(k = 0; k < ArrayCount(r.manifest); k++) if(r.manifest[k].id == String(p.id)) manifest = r.manifest[k];
|
|
236
|
+
if(manifest == null || manifest.type != String(p.type)) fail('ManifestMismatch','Native package identity differs from inspected archive');
|
|
237
|
+
type = String(p.type);
|
|
238
|
+
if(type != 'objects' && type != 'courses' && type != 'web' && type != 'custom_file') fail('UnsupportedPackageType',type);
|
|
239
|
+
if(type == 'custom_file' && (!StrBegins(String(p.base_url),'x-local://custom/') || StrContains(String(p.base_url),'..') || StrContains(String(p.base_url),'%') || StrContains(String(p.base_url),'\\'))) fail('UnsafeDestination','custom_file destination must be below x-local://custom/');
|
|
240
|
+
version = '';
|
|
241
|
+
if(type == 'objects') {
|
|
242
|
+
if(String(p.temp_package_url) != '') current = OpenDoc(String(p.temp_package_url) + '/update.xml').TopElem;
|
|
243
|
+
else current = OpenDoc(String(form.temp_package_url) + '/' + String(p.url)).TopElem;
|
|
244
|
+
version = String(current.basic.server_version);
|
|
245
|
+
}
|
|
246
|
+
downloads = ArraySelectAll(XQuery('for $d in download_packages where $d/package_id = ' + CodeLiteral(String(p.id)) + ' return $d'));
|
|
247
|
+
existing = ArrayCount(downloads) > 0;
|
|
248
|
+
for(j = 0; j < ArrayCount(downloads); j++) before.push(StrInt(downloads[j].id));
|
|
249
|
+
info = {id:String(p.id),type:type,versionMismatch:(version != '' && version != serverVersion),alreadyImported:existing,objects:[]};
|
|
250
|
+
p.selected = has(r.selectedPackages,String(p.id)) && (type == 'objects' || r.includeFiles);
|
|
251
|
+
if(p.selected && r.operation == 'import') {
|
|
252
|
+
selectedCount++;
|
|
253
|
+
if(info.versionMismatch && !r.allowVersionMismatch) fail('VersionMismatch','Package version differs from target');
|
|
254
|
+
if(existing && !r.allowReimport) fail('Reimport','Package was already imported');
|
|
255
|
+
}
|
|
256
|
+
p.selected_custom_templates = r.includeCustomTemplates; p.selected_roles = r.includeAccessRoles;
|
|
257
|
+
p.selected_lists = r.includeLists; p.selected_deleted_objects = r.includeDeletions; p.selected_objects = true;
|
|
258
|
+
if(ArrayCount(p.objects) != manifest.objectCount) fail('ManifestMismatch','Native object count differs from archive');
|
|
259
|
+
for(j = 0; j < ArrayCount(p.objects); j++) {
|
|
260
|
+
o = p.objects[j]; known = null;
|
|
261
|
+
try {known = manifest.objectTypes[StrInt(o.id)];} catch(missing) {}
|
|
262
|
+
if(known == null || known != String(o.type)) fail('ManifestMismatch','Native object identity/type differs from archive');
|
|
263
|
+
current = null;
|
|
264
|
+
try {current = OpenDoc(UrlFromDocID(o.id)).TopElem.Name;} catch(absent) {}
|
|
265
|
+
found = current != null && current != String(o.type);
|
|
266
|
+
info.objects.push({id:StrInt(o.id),conflict:found});
|
|
267
|
+
o.selected = has(r.selectedObjects,StrInt(o.id));
|
|
268
|
+
o.id_exists_type = 'valid';
|
|
269
|
+
if(found && p.selected && o.selected && r.operation == 'import') {
|
|
270
|
+
if(!r.skipConflictingIds) fail('TypeConflict','An object ID exists with a different type');
|
|
271
|
+
o.selected = false; o.id_exists_type = 'skip';
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
parts.push(info);
|
|
275
|
+
}
|
|
276
|
+
var formXml = form.GetXml();
|
|
277
|
+
if(StrCharCount(formXml) > 33554432) fail('OutputLimit','Native preview exceeds XML limit');
|
|
278
|
+
PutFileData(UrlToFilePath(root + '/view.xml'),formXml);
|
|
279
|
+
PutFileData(UrlToFilePath(root + '/source.json'),EncodeJson({sourceId:r.sourceId,sha256:r.sha256,targetId:receipt.targetId,accountId:receipt.accountId}));
|
|
280
|
+
if(r.operation == 'preview') {
|
|
281
|
+
cleanup();receipt.phase = 'inspected';receipt.status = 'completed';persist();
|
|
282
|
+
return {serverVersion:serverVersion,parts:parts,operation:receipt};
|
|
283
|
+
}
|
|
284
|
+
phase = 'import';receipt.phase = phase;persist();applied = true;
|
|
285
|
+
var outcome = tools.uni_process_package(url,form);
|
|
286
|
+
receipt.status = outcome.error == 0 && outcome.progress_count >= selectedCount ? 'completed' : 'partial';
|
|
287
|
+
receipt.error = StrLeftRange(String(outcome.error_text),2000);
|
|
288
|
+
phase = 'reports';receipt.phase = phase;persist();
|
|
289
|
+
var id; var wasBefore; var doc; var rowsReports; var report;
|
|
290
|
+
for(i = 0; i < ArrayCount(parts); i++) {
|
|
291
|
+
rows = ArraySelectAll(XQuery('for $d in download_packages where $d/package_id = ' + CodeLiteral(parts[i].id) + ' return $d'));
|
|
292
|
+
for(j = 0; j < ArrayCount(rows); j++) {
|
|
293
|
+
id = StrInt(rows[j].id);wasBefore = false;
|
|
294
|
+
for(k = 0; k < ArrayCount(before); k++) if(before[k] == id) wasBefore = true;
|
|
295
|
+
if(!wasBefore) {
|
|
296
|
+
if(ArrayCount(receipt.downloadIds) >= 1000) fail('OutputLimit','Download report count exceeds limit');
|
|
297
|
+
receipt.downloadIds.push(id);doc = OpenDoc(UrlFromDocID(rows[j].id));reportUrls.push(String(doc.TopElem.local_file_url));
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
PutFileData(UrlToFilePath(root + '/download-urls.json'),EncodeJson(reportUrls));persist();
|
|
302
|
+
for(i = 0; i < ArrayCount(reportUrls); i++) {
|
|
303
|
+
rowsReports = ArraySelectAll(XQuery('for $r in action_reports where $r/type = "download_package" and $r/data_file_url = ' + CodeLiteral(reportUrls[i]) + ' return $r'));
|
|
304
|
+
for(j = 0; j < ArrayCount(rowsReports); j++) {
|
|
305
|
+
if(ArrayCount(receipt.reportIds) >= 1000) fail('OutputLimit','Action report count exceeds limit');
|
|
306
|
+
receipt.reportIds.push(StrInt(rowsReports[j].id));
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
cleanup();receipt.phase = 'finished';persist();return receipt;
|
|
310
|
+
} catch(error) {
|
|
311
|
+
try {cleanup();} catch(cleanupError) {}
|
|
312
|
+
receipt.phase = phase;receipt.error = StrLeftRange(String(error),2000);receipt.status = applied ? 'unknown' : 'failed';
|
|
313
|
+
try {persist();} catch(receiptError) {}
|
|
314
|
+
// Outer operation preserves a structured native error instead of losing the operation ID.
|
|
315
|
+
return {nativeFailure:true,code:code,message:receipt.error,phase:phase,status:(applied ? 'unknown' : 'not_attempted')};
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
return EncodeJson(EncodeJson(BtPackageOperation(ParseJson('${request}'))));
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// Shared bounded native XML/date/ordinary-value projection.
|
|
2
|
+
var _btValueValues = 0;
|
|
3
|
+
function _btValueCheck(depth) {
|
|
4
|
+
if (depth > 32) throw 'Value projection exceeds depth limit (32)';
|
|
5
|
+
_btValueValues++;
|
|
6
|
+
if (_btValueValues > 10000) throw 'Value projection exceeds values limit (10000)';
|
|
7
|
+
}
|
|
8
|
+
function _btValueScalar(value) {
|
|
9
|
+
var kind = DataType(value);
|
|
10
|
+
// JSON-string transport protects CR/LF from SOAP XML normalization.
|
|
11
|
+
// Dates are an explicit ISO-string projection, not generic SOAP date support.
|
|
12
|
+
if ((kind == 'string') || (kind == 'date')) return EncodeJson(value);
|
|
13
|
+
if ((kind == 'integer') || (kind == 'real') || (kind == 'bool') || (kind == 'null') || (kind == 'undefined')) return value;
|
|
14
|
+
throw 'Value projection encountered an unsupported scalar';
|
|
15
|
+
}
|
|
16
|
+
function _btValueProject(value, depth) {
|
|
17
|
+
_btValueCheck(depth);
|
|
18
|
+
if (DataType(value) != 'object') return _btValueScalar(value);
|
|
19
|
+
var kind = ObjectType(value);
|
|
20
|
+
var entries = [];
|
|
21
|
+
var repeated = [];
|
|
22
|
+
var result;
|
|
23
|
+
var child;
|
|
24
|
+
var name;
|
|
25
|
+
var key;
|
|
26
|
+
var projected;
|
|
27
|
+
var multi;
|
|
28
|
+
var index;
|
|
29
|
+
var slot;
|
|
30
|
+
var search;
|
|
31
|
+
if (kind == 'XmElem') {
|
|
32
|
+
// Complex schema nodes have Type == '', including empty structures.
|
|
33
|
+
// Dynamic parents can have Type == 'string' with real children.
|
|
34
|
+
if ((value.ChildNum == 0) && (value.Type != '')) return _btValueScalar(value.Value);
|
|
35
|
+
if (value.ChildNum > 10000) throw 'Value projection exceeds values limit (10000)';
|
|
36
|
+
for (index = 0; index < value.ChildNum; index++) {
|
|
37
|
+
child = value[index];
|
|
38
|
+
name = child.Name;
|
|
39
|
+
key = EncodeJson(name);
|
|
40
|
+
multi = child.IsMultiElem;
|
|
41
|
+
// Indexed XmlElem instances are not XmlMultiElem collections.
|
|
42
|
+
// Name collisions with native XML properties must not prevent traversal.
|
|
43
|
+
try { multi = (multi || GetObjectProperty(value, name).IsMultiElem); } catch (err) { }
|
|
44
|
+
slot = -1;
|
|
45
|
+
for (search = 0; search < ArrayCount(entries); search++) {
|
|
46
|
+
if (entries[search][0] == key) { slot = search; break; }
|
|
47
|
+
}
|
|
48
|
+
projected = _btValueProject(child, depth + 1);
|
|
49
|
+
if (slot < 0) {
|
|
50
|
+
if (multi) {
|
|
51
|
+
_btValueCheck(depth + 1);
|
|
52
|
+
entries.push([key, [projected]]);
|
|
53
|
+
} else {
|
|
54
|
+
entries.push([key, projected]);
|
|
55
|
+
}
|
|
56
|
+
repeated.push(multi);
|
|
57
|
+
} else {
|
|
58
|
+
if (!repeated[slot]) {
|
|
59
|
+
_btValueCheck(depth + 1);
|
|
60
|
+
entries[slot][1] = [entries[slot][1]];
|
|
61
|
+
repeated[slot] = true;
|
|
62
|
+
}
|
|
63
|
+
entries[slot][1].push(projected);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return { entries: entries };
|
|
67
|
+
}
|
|
68
|
+
if (kind == 'JsArray') {
|
|
69
|
+
result = [];
|
|
70
|
+
if (ArrayCount(value) > 10000) throw 'Value projection exceeds values limit (10000)';
|
|
71
|
+
for (index = 0; index < ArrayCount(value); index++) result.push(_btValueProject(value[index], depth + 1));
|
|
72
|
+
return result;
|
|
73
|
+
}
|
|
74
|
+
if (kind == 'JsObject') {
|
|
75
|
+
for (name in value) entries.push([EncodeJson(name), _btValueProject(GetObjectProperty(value, name), depth + 1)]);
|
|
76
|
+
return { entries: entries };
|
|
77
|
+
}
|
|
78
|
+
throw 'Value projection encountered an unsupported object';
|
|
79
|
+
}
|
package/resources/xquery.bs
CHANGED
|
@@ -1,30 +1,22 @@
|
|
|
1
|
-
|
|
2
|
-
// Materialize only a bounded range; never ArrayCount the original lazy query result.
|
|
1
|
+
${projectionSource}
|
|
3
2
|
var _xqMaxRows = ${maxRows};
|
|
4
|
-
|
|
5
|
-
var
|
|
6
|
-
var
|
|
3
|
+
// Count only this materialized range, never the unbounded lazy source.
|
|
4
|
+
var _xqItems = ArraySelectAll(ArrayRange(XQuery(${queryLiteral}), 0, _xqMaxRows + 1));
|
|
5
|
+
var _xqRows = [];
|
|
6
|
+
var _xqChars = 0;
|
|
7
7
|
var _xqReason = null;
|
|
8
8
|
var _xqIndex;
|
|
9
9
|
var _xqRow;
|
|
10
|
-
var
|
|
10
|
+
var _xqSize;
|
|
11
11
|
for (_xqIndex = 0; _xqIndex < ArrayCount(_xqItems); _xqIndex++) {
|
|
12
|
-
if (
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
if (StrCharCount(_xqRows) + StrCharCount(_xqRow) + StrCharCount(_xqSeparator) > 65000) {
|
|
21
|
-
_xqReason = 'output';
|
|
22
|
-
break;
|
|
23
|
-
}
|
|
24
|
-
_xqRows = _xqRows + _xqSeparator + _xqRow;
|
|
25
|
-
_xqCount++;
|
|
12
|
+
if (ArrayCount(_xqRows) >= _xqMaxRows) { _xqReason = 'rows'; break; }
|
|
13
|
+
_xqRow = _btValueProject(_xqItems[_xqIndex], 0);
|
|
14
|
+
_xqSize = StrCharCount(EncodeJson(_xqRow)) + 1;
|
|
15
|
+
// At most four UTF-8 bytes per character, plus room for the envelope.
|
|
16
|
+
// A complete row is projected before checking its size: no memory/work bound.
|
|
17
|
+
if ((_xqChars + _xqSize) > 65000) { _xqReason = 'output'; break; }
|
|
18
|
+
_xqRows.push(_xqRow);
|
|
19
|
+
_xqChars = _xqChars + _xqSize;
|
|
26
20
|
}
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
',"truncated":' + (_xqReason == null ? 'false' : 'true') + ',"limitReason":' + EncodeJson(_xqReason) + '}';
|
|
30
|
-
return EncodeJson(_xqJson);
|
|
21
|
+
var _xqTruncated = (_xqReason != null);
|
|
22
|
+
return { rows: _xqRows, returnedRows: ArrayCount(_xqRows), truncated: _xqTruncated, limitReason: _xqReason };
|